Itterate to a multidimensional array

Viewed 62

I am trying to iterate over this array in order to take all league values (league_id,name,type etc)

array:1 [▼
"api" => array:2 [▼
"results" => 970
"leagues" => array:970 [▼
  0 => array:13 [▼
    "league_id" => 1
    "name" => "World Cup"
    "type" => "Cup"
    "country" => "World"
    "country_code" => null
    "season" => 2018
    "season_start" => "2018-06-14"
    "season_end" => "2018-07-15"
    "logo" => "https://media.api-football.com/leagues/1.png"
    "flag" => null
    "standings" => 1
    "is_current" => 1
  ]
  1 => array:13 [▼
    "league_id" => 2
    "name" => "Premier League"
    "type" => "League"
    "country" => "England"
    "country_code" => "GB"
    "season" => 2018
    "season_start" => "2018-08-10"
    "season_end" => "2019-05-12"
    "logo" => "https://media.api-football.com/leagues/2.png"
    "flag" => "https://media.api-football.com/flags/gb.svg"
    "standings" => 1
    "is_current" => 0
  ]
  .......

but until now,with the following code:

$request = json_decode($request->getBody()->getContents(), true);
foreach ($request as $array=>$val) {
   foreach ($val['leagues'] as $id) {
        dd($id);
   }
}

the only thing that i can get is the first array only and not the rest:

array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]

any help?

1 Answers

The dd() function you are calling is killing the execution of your script on your first iteration.

From the Laravel Docs:

The dd function dumps the given variables and ends execution of the script.

If you do not want to halt the execution of your script, use the dump function instead.

Just iterate over it like so:

$request = json_decode($request->getBody()->getContents(), true);
foreach ($request['leagues'] as $id=>$league) {
  print_r(compact('id', 'league')); // To see the id and value array
}

Hope this helps,

Related