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

PHP通过搜索找到正确的JSON元素,php,json,Php,Json,好吧,假设我有一个JSON的例子 { "result": [ { "id": 1, "title": "Random Title 1", "description": "Random Description 1" }, { "id": 4, "title": "Random Title 2", "d

好吧,假设我有一个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\u编号
,但它与数组编号不同。以上是错误的。。。如何修复它,以便通过
id

进行搜索以下是我的答案:

foreach ($json_a['tstJSON'] as $element) {
    if ($element['id'] == $getID) {
        $getit = $element['title'];
    }
}
<?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>");

?>


希望这是您需要的

和一个。谢谢,这很简单。谢谢。你知道你在if语句中做作业,对吗?