我目前正在使用PDO fetchAll()函數將菜單數據拉出數據庫。這樣做將查詢結果的每一行到一個數組的結構如下:使用重複值(PHP)創建具有重複值的MySQL結果的多維嵌套數組
Array (
[0] => Array (
[MenuId] => mmnlinlm08l6r7e8ju53n1f58
[MenuName] => Main Menu
[SectionId] => eq44ip4y7qqexzqd7kjsdwh5p
[SubmenuName] => Salads & Appetizers
[ItemName] => Tomato Salad
[Description] => Cucumbers, peppers, scallions and cured tuna
[Price] => $7.00)
[1] => Array (
[MenuId] => mmnlinlm08l6r7e8ju53n1f58
[MenuName] => Main Menu
[SectionId] => xlkadsj92laada9082lkas
[SubmenuName] => Entrees
[ItemName] => Portabello Carpaccio
[Description] => Dried tomatoes, pin nuts, mahon cheese
[Prices] => $18.00)
)
...etc.
爲了解析的原因,我想有數組沒有重複的值出現在嵌套結構:
Array (
[MenuName] => Main Menu
[MenuId] => mmnlinlm08l6r7e8ju53n1f58
[Section] => Array (
[SectionId] => eq44ip4y7qqexzqd7kjsdwh5p
[SubmenuName] => Salads & Appetizers
[Items] => Array (
[ItemName] => Tomato Salad
[Description] => Cucumbers, peppers, scallions and cured tuna
[Prices] => Array (
[PriceId] => xksjslkajiak1
[Price] => $7.00)
)
[SectionId] => xlkadsj92laada9082lkas
[SubmenuName] => Entrees
[Items] => Array (
[ItemName] => Portabello Carpaccio
[Description] => Dried tomatoes, pin nuts, mahon cheese
[Prices] => Array (
[PriceId => alkadh29189s09
[Price] = $8.00)
)
)
)
作爲一個n00b程序員,我一直在努力研究如何創建這個新的多維數組,最後一天一直在絞盡腦汁。看起來我可能不得不使用一對嵌套的foreach語句和引用,但我很難得到任何工作。
有誰知道我該怎麼做?
是您的數據嚴格的等級只是細微的變化,你可以做到嗎?換句話說,項目總是分組在一個子菜單中,子菜單分組在一個分區中,分區分組在一個菜單中? 如果是這樣,在你的SQL查詢中,按照那些(菜單,節,子菜單)進行排序,然後當你迭代你的結果時,檢查每個級別沒有改變並添加你的數組。 – Aerik 2012-04-06 21:11:57
嗨Aerik,是的,每個項目總是分組成一個子菜單,每個子菜單分組成一個菜單。我的SQL結果目前以這種方式排序,因此,例如,主菜單>開胃菜中的所有項目都組合在一起。 – idubs11 2012-04-06 21:36:05