2
所以,我得到這個陣列(將數據從數據庫收集):Recursivly ordenate陣列ID和PARENT_ID結構
Array
(
[0] => Array
(
[id] => 1
[parent_id] => 0
)
[1] => Array
(
[id] => 2
[parent_id] => 0
)
[2] => Array
(
[id] => 3
[parent_id] => 2
)
[3] => Array
(
[id] => 4
[parent_id] => 2
)
[4] => Array
(
[id] => 5
[parent_id] => 4
)
)
,我試圖創造和有序排列是這樣的:
Array
(
[1] => Array
(
[parent_id] => 0
)
[2] => Array
(
[parent_id] => 0
[children] => Array
(
[3] => Array
(
[parent_id] => 2
)
[4] => Array
(
[parent_id] => 2
[children] => Array
(
[5] => Array
(
[parent_id] => 4
)
)
)
)
)
)
,我嘗試用下面的代碼:
function placeInParent(&$newList, $item)
{
if (isset($newList[$item['parent_id']]))
{
$newList[$item['parent_id']]['children'][$item['id']] = $item;
return true;
}
foreach ($newList as $newItem)
{
if (isset($newItem['children']))
{
if (placeInParent($newItem['children'], $item))
{
return true;
}
}
}
return false;
}
$oldList = (first array above)
$newList = array();
foreach ($oldList as $item)
{
if ($item['parent_id'] == 0)
{
$newList[$item['id']] = $item;
}
else
{
placeInParent($newList, $item);
}
}
但問題是,我只得到第一個2級的ARR的唉!最後一個是失敗..和我的有序陣列結果是這樣的:
Array
(
[1] => Array
(
[parent_id] => 0
)
[2] => Array
(
[parent_id] => 0
[children] => Array
(
[3] => Array
(
[parent_id] => 2
)
[4] => Array
(
[parent_id] => 2
)
)
)
)
我只是無法得到我搞亂:\ help?
那麼......它的工作完美!我從來沒有想過這會是「這麼簡單」!我想我會「過度思考」,並努力去實現它(而且應該是錯誤的)。 唯一的問題是,我不完全理解代碼:\請問,請解釋一下嗎? – MGP
@MARCOGPINTO你不瞭解什麼? – Gumbo
我有點理解邏輯,但讓我們想象一下,我想添加一個字段,將路徑保存到該節點,例如,對於節點5,我保存2-4-5。我沒有準確地知道我在哪裏可以做到這一點..:\ – MGP