Reputation: 21
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;
}
}
Upvotes: 0
Views: 11319
Reputation: 4946
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'];
}
Upvotes: 2
Reputation: 4033
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"];
Upvotes: 0
Reputation: 162
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'];
Upvotes: 0
Reputation: 2118
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);
}
Upvotes: 1