Mann87
Mann87

Reputation: 324

recursive loop to get values from php array

I search a Solution to get all values from [BrowseNodeId] and [Name] from all [Ancestors] in a new array called categories. I think it must be a recursive loop, but how?

Array (
    [BrowseNodeId] => 343505011
    [Name] => Kinderzimmer
    [Ancestors] => Array (
        [BrowseNode] => Array (
            [BrowseNodeId] => 3517801
            [Name] => Möbel
            [Ancestors] => Array (
                [BrowseNode] => Array (
                    [BrowseNodeId] => 3312261
                    [Name] => Möbel & Wohnaccessoires
                    [Ancestors] => Array (
                        [BrowseNode] => Array (
                            [BrowseNodeId] => 3169011
                            [Name] => Kategorien
                            [IsCategoryRoot] => 1
                            [Ancestors] => Array (
                                [BrowseNode] => Array (
                                    [BrowseNodeId] => 3167641
                                    [Name] => Küche & Haushalt
                                )
                            )
                        )
                    )
                )
            )
        )
    )
) 

Upvotes: 0

Views: 121

Answers (1)

Bogdan
Bogdan

Reputation: 397

Try something like this

function getAllInfo($inputArray, $outputArray = array()) {
    $outputArray[] = array(
        'BrowseNodeId' => $inputArray['BrowseNodeId'],
        'Name' => $inputArray['Name']
    );
    if(isset($inputArray['Ancestors']['BrowseNode'])) {     
        return getAllInfo($inputArray['Ancestors']['BrowseNode'], $outputArray);
    }
    return $outputArray;    
}

See it in action here (with the test array you provided): http://3v4l.org/jd7hY

Upvotes: 1

Related Questions