PHP - 从面包屑列表的多维关联数组返回父数组

时间:2012-12-24 11:50:45

标签: php arrays breadcrumbs associative multidimensional-array

我正在尝试从数组创建动态面包屑。所以我可以添加到数组而不必手动更新面包屑。

好的,这是我的阵列的片段:(它不会更深入)

$menu = array(
    'Dashboard' => array(
        'Projects' => array(
            'Project 1' => array(
                'Project settings' => 'projects/project_1/settings',
                'Issue Tracker' => 'projects/project_1/issue_tracker',
                'Customize page' => 'projects/project_1',
                'Manage files' => 'projects/project_1/files',
            ),
            'Project 2' => array(
                'Project settings' => 'projects/project_2/settings',
                'Issue Tracker' => 'projects/project_2/issue_tracker',
                'Customize page' => 'projects/project_2',
                'Manage files' => 'projects/project_2/files',
            ),
        ),
        'Logout' => '#',
    )
);

我希望能够以一种我可以在以后迭代的方式返回任何密钥的所有父项。例如,对于“项目设置”:

'Dashboard','Projects','Project 1'.

1 个答案:

答案 0 :(得分:3)

在您的示例中,实际上有两条路径:

Key 'Project settings' found: 'Projects' -> 'Project 1'
Key 'Project settings' found: 'Projects' -> 'Project 2'

您可以使用递归迭代器轻松解决此问题(请参阅RecursiveIteratorIterator它提供您所需的一切)。我选择它是因为它允许您更轻松地搜索并获取父级别键:

$search = 'Project settings';
$it     = new ParentKeysIterator($menu);
foreach ($it as $key) {
    if ($key !== $search) continue;
    printf("Key '%s' found: '%s'\n", $key, implode("' -> '", $it->key()));
}

ParentKeysIterator

class ParentKeysIterator extends RecursiveIteratorIterator
{
    public function __construct(array $array) {
        parent::__construct(new  RecursiveArrayIterator($array));
    }

    public function current() {
        return parent::key();
    }

    public function key() {
        return $this->getParentKeys();
    }


    public function getParentKeys() {
        $keys = [];
        for ($depth = $this->getDepth() - 1; $depth; $depth--) {
            array_unshift($keys, $this->getSubIterator($depth)->key());
        }
        return $keys;
    }
}