2
Hell0編碼器。我嘗試用BFS
遍歷多數陣列並修改數組。這個怎麼做?我的代碼片段是在下面的部分。它可以檢測數組,但我無法保存更改(我在代碼中添加了一些註釋)。如何通過修改bfs遍歷php數組
/**
* @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
檢查PHP函數array_walk_recursive –
經過,但似乎很難才達到所需的行爲原因array_walk_recursive遍歷每個鍵=>值對我的數組。認爲老玩bfs岩石,但保存更改是一個痛苦的... – userlond