1

I have this multi dimensional array that came from cURL api:

  Array
(
    [status] => 200
    [message] => Success
    [info] => Array
        (
            [NewRegUsers] => 0
            [TotRegUsers] => 6
            [shows] => Array
                (
                    [0] => Array
                        (
                            [keyword] => BANANA
                            [entries] => 1
                        )

                    [1] => Array
                        (
                            [keyword] => CHRISTMAS
                            [entries] => 1
                        )

                    [2] => Array
                        (
                            [keyword] => CONCERT
                            [entries] => 1
                        )

                    [3] => Array
                        (
                            [keyword] => EXTRA
                            [entries] => 1
                        )



                )

        )

) 

I'm trying to get the values of NewRegUsers,TotRegUsers and the values in [shows] and get the keyword and entries. I used this code :

foreach($data['info'] as  $value)
    { 
        foreach ($value  as $item){

            $shows .= ' <tr>
                        <td class="col1">'.$x.'. '.$item['keyword'].'</th>
                        <td>'.$item['entries'].'</td>
                    </tr>';
            $x ++ ;
        }

    }

I'm still puzzled with arrays. :(

kevin_marcus
  • 277
  • 1
  • 5
  • 19
  • Possible duplicate of [How can I access an array/object?](http://stackoverflow.com/questions/30680938/how-can-i-access-an-array-object) – user3942918 Apr 05 '17 at 03:04

2 Answers2

1

The data you want is nested 2 levels deep. For that you need 2 keys as in: $data['info']['shows'].

That gives you another array of arrays, which you can iterate using a normal foreach.

I have always found that this sort of thing is easier if you:

  • create an array to take the items, and join the array at the end
  • use sprintf to insert your data, as it is more readable.

Below is a sample of how it would work:

$shows=array();
$tr='<tr><td class="col1">%s</th><td>%s</td></tr>';
foreach($data['info']['shows'] as $item) {
    $shows[]=sprintf($tr,$item['keyword'],$item['keyword']);
}
$shows=implode('',$shows);
Manngo
  • 14,066
  • 10
  • 88
  • 110
0

You almost had it. I would do it in this manner:

foreach($data['info'] as  $info)
{
    $NewRegUsers = $info['NewRegUsers'];
    $TotRegUsers = $info['TotRegUsers'];

    foreach ($info['shows']  as $k => $show){
        $shows .= ' <tr>
                        <td class="col1">'.$k.'. '.$show['keyword'].'</th>
                        <td>'.$show['entries'].'</td>
                    </tr>';
    }

}
CodeGodie
  • 12,116
  • 6
  • 37
  • 66