how to add item to the json file formatted array

Adding another player

$tempArray = json_decode($inp, true);
array_push($tempArray['players'], array('name' => $data['username'], 'image' => $data['userimage'], 'roll_over_image' => 'tank.jpg'));

Updating matches

first match array

$tempArray['games'][0]['matches'];

second match array

$tempArray['games'][1]['matches'];

are now simple two dimensional arrays with keys player1id, player2id and winner - it should be easy to update these. After that you can encode the $tempArray back to json.


<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
    <?php
       //first copy your json data  data.json
        $str = file_get_contents('data.json');//get contents of your json file and store it in a string,bro small suggestion never keep any JSON data in ur html file its not safe.always keep json data in external file.
        $arr = json_decode($str, true);//decode it
         $arrne['players'] = "sadaadad";
         $arrne['image'] = "sadaadad";
         $arrne['roll_over_image'] = "sadaadad";
         array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
         $str = json_encode($arr);
        //now send evrything to ur data.json file using folowing code
         if (json_decode($str) != null)
           {
             $file = fopen('data.json','w');
             fwrite($file, $str);
             fclose($file);
           }
           else
           {
             //  invalid JSON, handle the error 
           }

        ?>
</body>


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. :)

Tags:

Php

File

Json

Post