0

好的,假设我有这个 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是如何间隔的吗?[4]因此,如果我想获得第二个“随机标题 2” ,那就不会了[2]。我的一些 JSON“id”正在跳过,因为我编辑 JSON 文件......无论如何,我现在想获得基于 .json 元素的 JSON 元素的标题id。每个 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

4

2 回答 2

1
foreach ($json_a['tstJSON'] as $element) {
    if ($element['id'] == $getID) {
        $getit = $element['title'];
    }
}
于 2013-01-13T21:38:15.077 回答
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>");

?>

希望这是你需要的

于 2013-01-13T21:41:00.023 回答