Jonathan Lyon
Jonathan Lyon

Reputation: 3952

How to loop through json array within an array php

I need help traversing an array within array, I only need to loop through certain arrays, for example, how would I just lop through the names array?

Array
(
    [@total_records] => 10
    [@total_matching_records] => 10
    [@available_records] => 200
    [@available_matching_records] => 12
    [query] => Array
        (
            [summary] => Array
                (
                    [emails] => Array
                        (
                            [0] => Array
                                (
                                    [content] => [email protected]
                                )

                        )

                )

        )

    [results] => Array
        (
            [person] => Array
                (
                    [@match_score] => 1
                    [summary] => Array
                        (
                            [names] => Array
                                (
                                    [0] => Array
                                        (
                                            [first] => Jonathan
                                            [last] => Lyon
                                            [display] => Jonathan Lyon
                                        )
                                    [1] => Array
                                        (
                                            [first] => Jonathan
                                            [last] => Jordan
                                            [display] => Jonathan Jordan
                                        )
                                )

I have tried this but can't get it to work:-

foreach($json_output['results']['person']['summary']['names'] as $key => $val) {
echo $key.": ".$val."</br>";
}

Any help would be greatly appreciated.

Thanks

Jonathan

Upvotes: 0

Views: 762

Answers (3)

s.webbandit
s.webbandit

Reputation: 17000

In your example you trying to echo $key. Key in your case $key is array index (integer). Are you sure you realy need that?

You nedd to change your code to:

foreach($json_output['results']['person']['summary']['names'] as $val) {
    echo $val['display']."</br>";
}

Upvotes: 1

Ron
Ron

Reputation: 1336

Have you tried this

foreach($json_output['results']['person']['summary']['names'] as $key => $val) {
    echo $key.": ".$val['display']."</br>";
}

?

Upvotes: 1

jbizzay
jbizzay

Reputation: 1

Are you getting any error output? That would help a lot. I can see also that $val in this case is an array so you don't want to echo that.

Upvotes: 0

Related Questions