user2234992 user2234992 - 3 months ago 8
JSON Question

how to add item to the json file formatted array

I am using using just 1 data to insert in my json file..
$data=$_POST['myusernamer'];

$inp = file_get_contents('7players.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('7players.json', $jsonData);


So this is how my json file looks..I just want add 1 player at the end..

{

"players":[
{

"name":"Moldova",
"image":"/Images/Moldova.jpg",
"roll_over_image":"tank.jpg"
},
{

"name":"Georgia",
"image":"/Images/georgia.gif",
"roll_over_image":"tank.jpg"
},
{

"name":"Belarus",
"image":"/Images/Belarus.gif",
"roll_over_image":"tank.jpg"
},
{

"name":"Armenia",
"image":"/Images/armenia.png",
"roll_over_image":"tank.jpg"
},
{

"name":"Kazahstan",
"image":"/Images/kazahstan.gif",
"roll_over_image":"tank.jpg"
},
{

"name":"Russia",
"image":"/Images/russia.gif",
"roll_over_image":"tank.jpg"
},
],


"games" : [

{

"matches" : [

{

"player1id":"*",
"player2id":"*",
"winner":"*"
},

{
"player1id":"*",
"player2id":"*",
"winner":"*"
},

{
"player1id":"*",
"player2id":"*",
"winner":"*"
},

{
"player1id":"*",
"player2id":7,
"winner":"*"
},

{
"player1id":"*",
"player2id":"*",
"winner":"*"
},

{
"player1id":"*",
"player2id":"*",
"winner":"*"
},

{
"player1id":"*",
"player2id":"*",
"winner":"*"
}
]
},

{

"matches" : [

{
"player1id":"*",
"player2id":"*",
"winner":"*"
},
{
"player1id":"*",
"player2id":"*",
"winner":"*"
},
{
"player1id":"*",
"player2id":"*",
"winner":"*"
},
{
"player1id":"*",
"player2id":7,
"winner":"*"
},
{
"player1id":"*",
"player2id":"*",
"winner":"*"
},
{
"player1id":"*",
"player2id":"*",
"winner":"*"
},
{
"player1id":"*",
"player2id":"*",
"winner":"*"
},

]
}
]
}


My question is how do I add player at the end? And I would also like to know how to update

player1id":"*",
"player2id":"*",
"winner":"


In the match array..Thanks you for reading this!! Thanks again...

Answer

Just decode your json string and then use array push

$tempArray = json_decode($jsonstring, true);
array_push($tempArray, $your_data);

For your case

    $str = '{ 

"players":[
   {

        "name":"Moldova",
        "image":"/Images/Moldova.jpg",
        "roll_over_image":"tank.jpg"
   },
   {

        "name":"Georgia",
        "image":"/Images/georgia.gif",
        "roll_over_image":"tank.jpg"
   } ]}';


 $arr = json_decode($str, true);
 $arrne['name'] = "dsds";
 array_push( $arr['players'], $arrne );
 print_r($arr);

Just check value of print_r($arr); I hope this is what you want. :)