PHP中的JSON操作?

PHP中的JSON操作?,php,json,Php,Json,我需要在JSON文件中编辑一些数据,我希望在PHP中这样做。我的JSON文件如下所示: [ { "field1":"data1-1", "field2":"data1-2" }, { "field1":"data2-1", "field2":"data2-2" } ] $arr = json_decode(file_get_contents(foo.json)); // first array ec

我需要在JSON文件中编辑一些数据,我希望在PHP中这样做。我的JSON文件如下所示:

[
    {
        "field1":"data1-1",
        "field2":"data1-2"
    },
    {
        "field1":"data2-1",
        "field2":"data2-2"
    }
]
$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;
$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'];

到目前为止,我所做的是
$data=json\u decode(file\u get\u contents(foo.json))
,但我不知道如何导航这个数组。例如,如果我想从第二个对象的第一个字段中查找数据,那么PHP语法是什么?另外,还有其他方法可以将JSON数据解析为PHP友好格式吗?

此JSON包含2个数组,每个数组有2个对象,您可以这样访问:

[
    {
        "field1":"data1-1",
        "field2":"data1-2"
    },
    {
        "field1":"data2-1",
        "field2":"data2-2"
    }
]
$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;
$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'];
如果将其转换为数组并避开对象,则可以如下方式访问:

[
    {
        "field1":"data1-1",
        "field2":"data1-2"
    },
    {
        "field1":"data2-1",
        "field2":"data2-2"
    }
]
$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;
$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'];

请使用此代码浏览json格式。此代码是动态的,可以在结果中导航任意数量的对象

<?php
$json ='[
    {
        "field1":"data1-1",
        "field2":"data1-2"
    },
    {
        "field1":"data2-1",
        "field2":"data2-2"
    }
]';

if($encoded=json_decode($json,true))
{
    echo 'encoded';

    // loop through the json values
    foreach($encoded as $key=>$value)
    {
        echo'<br>object index: '.$key.'<br>';
        foreach($value as $bKey=>$bValue)
        {
            echo '<br>&nbsp;&nbsp;'.$bValue.' = '.$bValue;
        }

    }
    // get a perticular item
    echo '<br>object[0][field1]: '.$encoded[0]['field1'];

}
else
{
    echo'error on syntax';


}
?>

这就成功了。谢谢你!如果您执行
json\u解码(file\u get\u contents(foo.json),true)
您将获得一个通常比对象更容易使用的assoc数组。