PHP在JSON中查找值

时间:2014-04-02 14:37:23

标签: php json

我不知道为什么这不起作用。计数返回时阵列的大小正确。

这是mWeb.json文件:

    [{"Title": "Some-Name","h1": "Some-h1-words", "Comments": "Some Comment", "Comments2": "Some Comment2"},
{"Title": "Some-Name b","h1": "Some-h1-words b", "Comments": "Some Comment b", "Comments2": "Some Comment2 b"},
{"Title": "Some-Name c","h1": "Some-h1-words c", "Comments": "Some Comment c", "Comments2": "Some Comment2 c"}]

以下是代码:

    <?
$url = 'mWeb.json';
$JSON = file_get_contents($url);
    $someName = "Some-Name";    
$data = json_decode($JSON);
echo count($data);
for($x=0; $x<count($data); $x++){
    if($data[$x]['Title']==$someName){
        echo '[{"Title":"'.$data[$x]["Title"].'","h1":"'.$data[$x]["h1"].'","Comments":"'.$data[$x]["Comments"].'","Comments2":"'.$data[$x]['Comments2'].'"}]';
    }
}
?>

所有回波都是数组的长度 - 回显计数($ data);

1 个答案:

答案 0 :(得分:6)

如果你var_dump($data),你会发现你的对象是......对象!

要获取关联数组,请执行以下操作:

$data = json_decode($JSON,true);