我目前正在使用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)
)
)
)
作为一名n00b程序员,我在最后一天试图弄清楚如何创建这个新的多维数组.看起来我可能不得不使用几个嵌套的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);