递归循环从php数组中获取值

时间:2015-01-14 21:09:58

标签: php loops for-loop recursion foreach

我搜索一个解决方案,从名为categories的新数组中获取[BrowseNodeId][Name]中所有[Ancestors]的值。我认为它必须是一个递归循环,但是如何?

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
                                )
                            )
                        )
                    )
                )
            )
        )
    )
) 

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

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;    
}

在此处查看此操作(使用您提供的测试数组):http://3v4l.org/jd7hY