PHP通过搜索找到正确的JSON元素

时间:2013-01-13 21:34:21

标签: php json

好吧,假设我有JSON的这个例子

{
    "result": [
        {
            "id": 1,
            "title": "Random Title 1",
            "description": "Random Description 1"
        },
        {
            "id": 4,
            "title": "Random Title 2",
            "description": "Random Description 2"
        },
        {
            "id": 10,
            "title": "Random Title 3",
            "description": "Random Description 3"
        }
    ]
}

你注意到ID是如何分开的吗?因此,如果我想获得第二个“随机标题2”,它将不是[4]而是[2]。我的一些JSON“ID”正在跳过,因为我编辑了JSON文件...现在,我想获得基于id的JSON元素的标题。每个JSON元素都有不同的ID。

这就是我现在所做的事情:

$string = file_get_contents("achievements.json");
$json_a=json_decode($string,true);

$getID = $ID_number;

$getit = $json_a['testJSON'][$getID]['title'];

现在,我有$ID_number,但它与数组编号不同。以上是错误的...如何修复它,以便我按id

进行搜索

2 个答案:

答案 0 :(得分:1)

foreach ($json_a['tstJSON'] as $element) {
    if ($element['id'] == $getID) {
        $getit = $element['title'];
    }
}

答案 1 :(得分:1)

以下是我的回答:

<?php

$json = <<<EOF
{
    "result": [
        {
            "id": 1,
            "title": "Random Title 1",
            "description": "Random Description 1"
        },
        {
            "id": 4,
            "title": "Random Title 2",
            "description": "Random Description 2"
        },
        {
            "id": 10,
            "title": "Random Title 3",
            "description": "Random Description 3"
        }
    ]
}
EOF;

$arr = json_decode($json,true);
$res = $arr['result'];

function search_by_key_and_value($array, $key, $value)
{
    $results = array();

    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;

        foreach ($array as $subarray)
            $results = array_merge($results, search_by_key_and_value($subarray, $key, $value));
    }

    return $results;
}

print("<pre>");
print_r($res);
print("</pre>");

print("<hr />");
$result = search_by_key_and_value($res,"id",4);

print("<pre>");
print_r($result);
print("</pre>");

?>

希望这是你需要的