2
我需要分層排列對象數組。數據看起來像這樣:使用PHP將數據排序爲多維分層陣列
array (size=54)
0 =>
object(stdClass)[786]
public 'term_id' => string '1' (length=3)
public 'name' => string 'Boots' (length=25)
public 'parent' => string '0' (length=3)
1 =>
object(stdClass)[785]
public 'term_id' => string '2' (length=3)
public 'name' => string 'Dresses' (length=25)
public 'parent' => string '1' (length=3)
2 =>
object(stdClass)[786]
public 'term_id' => string '3' (length=3)
public 'name' => string 'Scarves' (length=25)
public 'parent' => string '2' (length=3)
3 =>
object(stdClass)[785]
public 'term_id' => string '4' (length=3)
public 'name' => string 'Gloves' (length=25)
public 'parent' => string '1' (length=3)
我想創建一個多維數組,可以顯示「父級和子級」的層次結構。每個對象的parent
屬性指的是另一個對象的term_id
。
結果會是這個樣子:
array (size=54)
0 =>
object(stdClass)[786]
public 'term_id' => string '1' (length=3)
public 'name' => string 'Boots' (length=25)
public 'parent' => string '0' (length=3)
public 'children' => array (size=2)
0 =>
object(stdClass)[785]
public 'term_id' => string '2' (length=3)
public 'name' => string 'Dresses' (length=25)
public 'parent' => string '1' (length=3)
public 'children' => (size=1)
0 =>
object(stdClass)[786]
public 'term_id' => string '3' (length=3)
public 'name' => string 'Scarves' (length=25)
public 'parent' => string '2' (length=3)
1 =>
object(stdClass)[785]
public 'term_id' => string '4' (length=3)
public 'name' => string 'Gloves' (length=25)
public 'parent' => string '1' (length=3)
到目前爲止,我想出了這個代碼:
$sortedCategories = array();
foreach($shopCategories as $shopCategory) {
$tmp = $shopCategory;
foreach($shopCategories as $category) {
if ($tmp->term_id == $category->parent) {
$tmp->children[] = $category;
$sortedCategories[] = $tmp;
}
}
}
,但我不能把它與多級層次結構的工作。
如何對數據進行排序以實現所需的結果?
完美地工作。我只有一個問題。爲什麼通過引用'build_tree'函數傳遞'$ a'?這是必要的嗎?萬分感謝! – luqo33 2015-04-02 15:10:58
我不會以任何方式改變$ a,所以沒有理由複製整個數組。那隻會浪費時間和記憶。 – kainaw 2015-04-02 15:53:08
這是一個非常合理的觀點。我必須說你在你的回覆中提出的腳本看起來非常簡潔明瞭,但我發現很難在腦海中重新找回腳步。我絕對需要練習.. – luqo33 2015-04-02 21:42:15