简体   繁体   中英

PHP get array value from json

Using PHP, how would I access the inner array values, specific to this example the values specific to each game array, from a json feed similar to this:

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] =>
            )

I have tried nesting a foreach loop inside a foreach loop similar to this:

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

If that is an array you are looking at then you can reach the values

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

This should give you the values within each array in the games section.

EDIT: to answer additional question in comment

To get the specific values of the game like the id , the second foreach loop will not be needed. Instead do the following:

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

You just access it as an associative array.

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

You can loop through the games like so:

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

If you are trying to access this,

    [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] =>
        )

..then you are doing it right. The only problem is you are trying to echo an array. Trying using print_r($value) . If you want a specific value, like the id. You can echo $value['id'];

I think you could use one of the many example of recursive array_key_search. This way you could simply do :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM