1

I have an array of arrays. I am trying to loops through each of it and get values. Here is the code I am using to go into the array,

        $body = json_decode($res->getBody(),true); //gets the whole json and make an array
        $events = $body['results']; // to go one level down and get 'results'
        //var_dump($events);

        foreach ($events as $obj) {
            var_dump($obj); // to go into the array of arrays and print each inside array.
           break;
        }

Array I need to loop:

array(1) {
  ["events"]=>
  array(43) {
    [0]=>
    array(22) {
      ["item1"]=>
      string(71) "lorem ipsum bla bla"
      ["lorem ipsum bla bla"]=>
      string(21) "lorem ipsum bla bla"
      ["lorem ipsum bla bla"]=>
      string(17) "lorem ipsum bla bla"
      ["lorem ipsum bla bla"]=>
      string(10) "lorem ipsum bla bla"
 }
    [1]=>
    array(22) {
      ["item1"]=>
      string(71) "lorem ipsum bla bla"
      ["lorem ipsum bla bla"]=>
      string(21) "lorem ipsum bla bla"
      ["lorem ipsum bla bla"]=>
      string(17) "lorem ipsum bla bla"
      ["lorem ipsum bla bla"]=>
      string(10) "lorem ipsum bla bla"
}

What the array shows when I loop over a single item:

It shows me the complete array

1
  • To clarify you want to loop over $events['events']? Commented Oct 21, 2018 at 12:06

3 Answers 3

2

I think you should try like this way with foreach() to iterate the 0th index of $events,

foreach($events[0]['events'] as $obj) {
    print '<pre>';
    print_r($obj);
    print '</pre>';
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to loop over $events['events'] then you should set that as the first parameter of the foreach

foreach($events['events'] as $obj) {
    var_dump($obj);
}

2 Comments

When I do this, it says "Undefined index: events"
What's the output of var_dump(array_keys($events)); before the foreach?
0

Here is as function i have made in order to visualize your array in the most understandable way:

function DebugArray($arr){
    $s='';
    if($arr==null){
        $s .= 'NULL';
        return $s;
    }
    $s .=  '<table border="1">';
    foreach((array)$arr as $k=>$v){
        $s .=  '<tr><td>'.$k.'</td><td>';
        if( is_array($v) ){
            $s .= DebugArray($v);
        }else{
            $s .=  $v;
        }
        $s .=  '</td></tr>';
    }
    $s .=  '</table>';
    return $s;
}

Pretty useful to see fast all the multi dimensions Hope it will help

Comments