Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON manipulation in PHP?

Tags:

json

php

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:

[
    {
        "field1":"data1-1",
        "field2":"data1-2"
    },
    {
        "field1":"data2-1",
        "field2":"data2-2"
    }
]

What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?

like image 320
wbadart Avatar asked Oct 15 '25 17:10

wbadart


2 Answers

This JSON contains 2 arrays with 2 objects each, you can access like this:

$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;

if you convert this to an array and avoid objects you can then access like this:

$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
like image 190
Danny Broadbent Avatar answered Oct 18 '25 12:10

Danny Broadbent


$data = json_decode(file_get_contents(foo.json)); 
foreach($data as $k => &$obj) {

    $obj->field1 = 'new-data1-1';
    $obj->field2 = 'new-data1-2';

}
like image 27
Aleksandr Ivin Avatar answered Oct 18 '25 11:10

Aleksandr Ivin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!