2

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

好的,这是我的数组的一个片段:(不会更深入)

$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'.
4

1 回答 1

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;
    }
}
于 2012-12-24T12:10:35.923 回答