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. :(

0

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

bro this code works fine. but how will i get the [NewRegUsers] and [TotRegUsers] ?
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>';
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.