【问题标题】:How to use JSON with unknown multiple keys (PHP)如何使用带有未知多个键的 JSON (PHP)
【发布时间】:2013-03-11 00:08:22
【问题描述】:

我收到一个 JSON 字符串,它有多个未知键。这很难解释,因为这些 JSON 字符串非常大,我会尝试以最有效的方式分解它们。

当我解码 JSON 字符串时,我使用 PHP 来分解我得到的对象。

$data1 = $json->result->map->12313214654[0]
$data2 = $json->result->map->12313214654[2]

$differentdata1 = $json->result->map->12313214655[0]

如您所见,map 键后面有不同的小节。 这些是数字,非常随机。而且它们的外观也不规则。所以有时只有一个小节(或数字),有时更多。 我怎样才能访问它们?我尝试使用$datacount = $count($json->result->map) 但它总是显示1。然后我仍然无法访问映射键的子元素。 有人对此有解决方案吗?

【问题讨论】:

  • 我在使用对象,所以我没有考虑 foreach!太明显了!非常感谢。

标签: php json key


【解决方案1】:

由于您似乎有未知数量的数组形式的数据,您可以使用 foreach 循环迭代您的结果:

foreach ($json->result->map as $key => $dataArray) {
    // $key will be the numeric key, e.g. 12313214654
    // $dataArray will be the array of data you're after
    foreach ($value as $dataIndex => $data) {
        // $dataIndex is the position of $data within the $dataArray
        // $data is the value you were trying to access with $json->result->map->12313214654[n]
        // You do your work with $data here. 
        print_r($data);
    } 
}

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 1970-01-01
    • 2019-09-27
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2019-01-06
    相关资源
    最近更新 更多