我有两个MySQL表,product和prodGroups。我需要以关联数组的这种格式检索以下数据:
Array ( [0] => Product Group 1 => Item 1
=> Item 2
=> Item 3
[1] => Product Group 2 => Item 4
=> Item 5
=> Item 6
[2] => Product Group 3 => Item 7
=> Item 8
=> Item 9 )
上面的代码是自由编写的,所以很明显,对于一个关联数组来说,这不是print_r的正确格式,但是希望你能理解。
我很难理解从MySQL表中检索项目,其中他们的prodGroup值与产品组1/2/3的名称相匹配。我希望属于特定产品组的项是其合法父数组的一部分。
我不擅长解释,希望我所写的足以说明我的问题。然而,总的来说,如果你仍然迷路了,我需要Item 1&2&3在数组中作为Product Group 1的一部分。伪代码将是伟大的,我有一种感觉,foreach循环是必需的,我只是完全失去了它的结构。
有两种解决方法:
1)使用嵌套查询。对于少量的数据,为什么不:
while($row = getNextProductGroup())
$row->items = getItemsForGroup($row->ProductGroupId);
2)如果你有大量的数据,这将是昂贵的性能,所以你需要一个更聪明的方法。把它们连在一起,然后在PHP中分开:
$productGroups = [];
while($row = getNextProductGroupAndItem()) {
if(!isset($productGroups[$row->ProductGroupId])) {
$row->items = [];
$productGroups[$row->ProductGroupId] = $row;
}
$productGroups[$row->ProductGroupId]->items[] = $row;
}