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。主要问题是将元素弹出/推送到数组。
<?
$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