我有两个 MySQL 表,products 和 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 )
上面的内容是自由编写的,很明显这不是 assoc 数组的 print_r 的正确格式,但希望您能理解。
我无法理解如何从 MySQL 表中检索项目,其中的 prodGroup 值与产品组 1/2/3 的名称相匹配。我希望属于特定产品组的项目与其合法的父数组分开。
我不是最擅长解释的人,希望我所写的内容足以说明我的问题。但是,总而言之,如果您仍然迷路,我需要项目 1&2&3 与数组中的产品组 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;
}
关于php - 使用 PHP 关联数组检索 MySQL 数据的伪代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16282730/