PHP从json获取数组值

时间:2013-10-04 02:28:28

标签: php arrays 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; 
}
}

4 个答案:

答案 0 :(得分:2)

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

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

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

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

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

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

答案 1 :(得分:1)

您只需将其作为关联数组访问。

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

你可以像这样循环游戏:

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

答案 2 :(得分:0)

如果您尝试访问此内容,

    [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'];

答案 3 :(得分:0)

我认为您可以使用递归array_key_search的{​​{3}}之一。这样你就可以做到:

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