如何使用修改后的 bfs 遍历 php 数组

How to traverse php array with bfs with modifications

Hell0 程序员。我尝试使用 BFS 遍历多数组并修改数组。这该怎么做?我的 bfs 片段在下面的部分中。它迭代数组,但我无法保存更改(我在代码中添加了一些注释)。

   /**
     * @param array $tree
     * @param callable $callable
     * @return array
     */
    function bfs($tree, $callable)
    {
        $mn = function($item) use($callable) {
            // preserve items for array traverse
            return $callable($item) + ['items' => $item['items']];
        };
        $queue = new \SplQueue();
        $start = $tree[0];
        $queue->enqueue($start);
        $visited = [$start['id']];
        while ($queue->count()) {
            $node = $queue->dequeue();
            foreach ($node['items'] as $item) {
                if (!in_array($item['id'], $visited)) {
                    $visited[] = $item['id'];
                    $queue->enqueue($item);
                    $item = $mn($item); // I need save modifications here
                }
            }
            $node = $mn($node); // I need save modifications here
        }
        return $tree;
    }

我的简化输入是:

[
    0 => [
        'id' => '1'
        'left_id' => '1'
        'right_id' => '8'
        'depth' => '0'
        'name' => 'Page level 1'
        'items' => [
            0 => [
                'id' => '4'
                'left_id' => '2'
                'right_id' => '5'
                'depth' => '1'
                'name' => 'Page level 1.1'
                'items' => []
            ]
        ]
    ]
]

我的输出需要像这样:

[
    0 => [
        'label' => 'Page level 1'
        'items' => [
            0 => [
                'label' => 'Page level 1.1'
                'items' => []
            ]
        ]
    ]
]

P.S。主要问题是pop/push元素到数组。

<? 
    $start = '23';
    $queue = [];
    // array_push($queue, &$start); causes Fatal error
    array_push($queue, $start); 
    $start2 = array_pop($queue); // I need get reference to $start
    $start2 = '24';
    echo $start; // needed result shoud be 24, i.e. to change $start by reference

这个有效

<?
    public function handleTree(&$array, $callback)
    {
        foreach ($array as &$item) {
            handleTree($item['items'], $callback);
            $item = $callback($item) + ['items' => $item['items']];
        }
    }