2

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?

2
  • 2
    you are calling dd, dump and die, so you are killing the script after the first iteration of that loop, so you are only accessing the first element of that array ... if you just want to dump data without killing the execution you can use dump($var) instead Commented Oct 20, 2019 at 22:33
  • 2
    Did you mean to do this instead: foreach ($request['leagues'] as $league) { print_r($league); }. Also if you use dd() it means die and dump, i.e. it will print the contents of the variable and then exit, so that;s probably why you are getting only the first item? Commented Oct 20, 2019 at 22:35

1 Answer 1

3

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,

Sign up to request clarification or add additional context in comments.

2 Comments

remove the dd
didn't realize what dd() was. Thanks,

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.