PHP 从 json 获取数组值


PHP get array value from json

使用 PHP,我将如何从类似于以下内容的 json 源访问内部数组值,特定于此示例的每个游戏数组的特定值:

Array
(
[startIndex] => 3
[refreshInterval] => 60
[games] => Array
    (
        [0] => Array
            (
                [id] => 2013020004
                [gs] => 5
                [ts] => WEDNESDAY 10/2
                [tsc] => final
                [bs] => FINAL
                [bsc] => final
            )
        [1] => Array
            (
                [id] => 2013020005
                [gs] => 5
                [ts] => WEDNESDAY 10/2
                [tsc] => final
                [bs] => FINAL
                [bsc] =>
            )

我尝试将一个 foreach 循环嵌套在类似于这样的 foreach 循环中:

foreach ($json as $key => $jsons) {
foreach ($jsons as $my => $value) {
    echo $value; 
}
}

如果这是您正在查看的数组,那么您可以达到以下值

foreach($json["games"] as $game) {
   foreach ($game as $key => $value) {
      echo $value; 
   }
}

这应该为您提供游戏部分每个数组中的值。

编辑:在评论中回答其他问题

要像id一样获得游戏的特定值,不需要第二个 foreach 循环。而是执行以下操作:

foreach($json["games"] as $game) {
   echo $game['id'];
}
您只需

将其作为关联数组访问即可。

$json['games'][0]['id'] // This is 2013020004
$json['games'][1]['id'] // This is 2013020005

您可以像这样循环浏览游戏:

foreach($json['games'] as $game){
   print_r($game);
}

如果您尝试访问它,

    [0] => Array
        (
            [id] => 2013020004
            [gs] => 5
            [ts] => WEDNESDAY 10/2
            [tsc] => final
            [bs] => FINAL
            [bsc] => final
        )
    [1] => Array
        (
            [id] => 2013020005
            [gs] => 5
            [ts] => WEDNESDAY 10/2
            [tsc] => final
            [bs] => FINAL
            [bsc] =>
        )

..那么你做对了。唯一的问题是您正在尝试回显数组。尝试使用print_r($value) .如果需要特定值,例如 id。你可以echo $value['id'];

我认为

你可以使用递归array_key_search的众多例子之一。这样你可以简单地做:

$firstGame = array_search_key(0, $array);
$firstGameId = $firstGame["id"];