timothepoznanski
timothepoznanski

Reputation: 1112

Add field to a JSON file

I have a very simple JSON file "json.txt" :

{
"status": true,

"data": 
{
    "clics": 
    [
        {
            "id": "1",
            "title": "Title 1",
            "comment": "Blablabla 1",
            "url": "http://photostodisplay/1.jpg"
        },
        {
            "id": "2",
            "Title": "Title 2",
            "comment": "Blablabla 2",
            "url": "http://photostodisplay/2.jpg"
        }
    ]
   }
}

and I would like to add data and get the following result :

{
"status": true,

"data": 
{
    "clics": 
    [
        {
            "id": "1",
            "title": "Title 1",
            "comment": "Blablabla 1",
            "url": "http://photostodisplay/1.jpg"
        },
        {
            "id": "2",
            "Title": "Title 2",
            "comment": "Blablabla 2",
            "url": "http://photostodisplay/2.jpg"
        },
        {
            "id": "3",
            "Title": "Title 3",
            "comment": "Blablabla 3",
            "url": "http://photostodisplay/3.jpg"
        }
    ]
  }
}

The php code I use return the following error :

Fatal error: Cannot use object of type stdClass as array in /home/XXXX/www/clic/test.php on line 10

Here is the php code

<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$newdata = array('id'=>'11', 'title' => 'sfdfsdfqf', 'comment' => 'sfdfwwfwdsdfqf', 'url' => 'sdfqwsfsdqqfqqqsfcq');
$data[] = $newdata;
file_put_contents($file, json_encode($data));
echo OK
?>

EDIT - Cezary answer gives almost what I need but is not. Here is what I get :

{

"status": true,

"data": {

  "clics": [

     {

        "id": "1",

        "title": "Title 1",

        "comment": "Blablabla 1",

        "url": "http://photostodisplay/1.jpg"

     },

     {

        "id": "2",

        "Title": "Title 2",

        "comment": "Blablabla 2",

        "url": "http://photostodisplay/2.jpg"

     }

  ]

},

"0": {

  "id": "11",

  "title": "sfdfsdfqf",

  "comment": "sfdfwwfwdsdfqf",

  "url": "sdfqwsfsdqqfqqqsfcq"

}

}

Upvotes: 1

Views: 1426

Answers (2)

patrick
patrick

Reputation: 11721

Shouldn't that be

$data["data"]["clics"][]=$newdata;

or

array_push($data["data"]["clics"],$newdata);

Upvotes: 0

Cezary Wojcik
Cezary Wojcik

Reputation: 21845

The issue lies with this bit of code:

$data = json_decode(file_get_contents($file));

This returns an object, not an associative array. Change that line to this:

$data = json_decode(file_get_contents($file), true);

The second argument in json_decode specifies whether you want an associative array or not, and it defaults to false.

EDIT:

You're currently adding something to the root array. To add to the clics array, you can replace $data[] = $newdata; with:

$data['data']['clics'][] = $newdata;

Upvotes: 3

Related Questions