我目前正在使用 PDO fetchAll() 函数从数据库中提取菜单数据。这样做会将查询结果的每一行放入以下结构的数组中:
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)
)
)
)
作为一名一流的程序员,我在最后一天绞尽脑汁试图弄清楚如何创建这个新的多维数组。看起来我可能必须使用几个嵌套的 foreach 语句和引用,但我很难让任何东西发挥作用。
有谁知道我该怎么做?
这看起来像您正在寻找的
$array = array() ;
while ($row = PDO::fetchAll()) // Replace with relevant Information
{
$section = array();
$items = array();
$prices = array();
if(!array_key_exists($row['MenuId'], $array))
{
$array[$row['MenuId']] = array();
$array[$row['MenuId']]['MenuName'] = $row['MenuName'] ;
$array[$row['MenuId']]['MenuId'] = $row['MenuId'] ;
$array[$row['MenuId']]['Section'] = array();
}
if(!array_key_exists($row['SectionId'], $array[$row['MenuId']]['Section']))
{
$array[$row['MenuId']]['Section'][$row['SectionId']] = array();
$array[$row['MenuId']]['Section'][$row['SectionId']]['SectionId'] = $row['SectionId'] ;
$array[$row['MenuId']]['Section'][$row['SectionId']]['SubmenuName'] = $row['SubmenuName'] ;
$array[$row['MenuId']]['Section'][$row['SectionId']]['Items'] = array() ;
}
$items['ItemName'] = $row['ItemName'] ;
$items['Description'] = $row['Description'] ;
$prices['PriceId'] = $row['PriceId'] ;
$prices['Price'] = $row['Price'] ;
$items['Prices'] = $prices ;
$section['Items'] = $items ;
$array[$row['MenuId']]['Section'][$row['SectionId']]['Items'][] = $items ;
}
var_dump($array);
只需进行微小的更改,您就可以实现您想要的效果
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)