0

我有一个 JSON 编码的数组,但其中一个数组值是数组名称中的“$”。当我使用下面的代码读取值时,没有得到我的值。

<?php
error_reporting("E_ERROR");
date_default_timezone_set("Europe/Amsterdam"); 
$json = file_get_contents('http://jotihunt.net/api/1.0/nieuws');
$json = json_decode($json, true);

foreach ($json as $key1 => $item) {
    foreach ($item as $key2 => $value) {

        $id = $item['$id'];

         echo gmdate("d-m-Y H:i", strtotime('+2 hours', $value['datum'])) . '&nbsp;' . $value['titel'] . ' met ID: '.$id.'<br/>';
    }
}
?>

下面的 JSON 数组来自$item

Array
(
    [0] => Array
        (
            [ID] => Array
                (
                    [$id] => 52532555a08789e17900000d /* Can't read this with $item[$id] because the "$" before "id" */
                )

            [titel] => API 1.0    /* $value['titel'] */
            [datum] => 1381180320 /* $value['datum'] */
        )

    [1] => Array
        (
            [ID] => Array
                (
                    [$id] => 524b16eaa08789806a000010
                )

            [titel] => Inschrijving gesloten
            [datum] => 1380652260
        )

有谁知道我怎么读$id

4

2 回答 2

3

$id 项目包含在 ID 项目中。尝试:

$id = $item['ID']['$id'];

编辑:我不确定你为什么有嵌套循环。这应该足够了:

foreach ($json as $key1 => $item) {
 $id = $item['ID']['$id'];
 echo gmdate("d-m-Y H:i", strtotime('+2 hours', $item['datum'])) . '&nbsp;' . $item['titel'] . ' met ID: '.$id.'<br/>';
}
于 2013-10-10T09:39:51.167 回答
1

使用$item['ID']['$id']. 如果您发现自己在使用$item[ID],则使用未定义的常量ID

这是有效的代码:

$json = file_get_contents('http://jotihunt.net/api/1.0/nieuws');
$json = json_decode($json, true);

foreach ($json['data'] as $key1 => $item) {
  $id = $item['ID']['$id'];
  echo gmdate("d-m-Y H:i", strtotime('+2 hours', $item['datum'])) . '&nbsp;' . $item['titel'] . ' met ID: '.$id.  '<br />';
}
于 2013-10-10T09:39:43.767 回答