我在另一篇关于如何从 SQL 返回的记录创建多维数组的帖子中发布了这个,因为在听到一些建议后我返回了重复的信息我来到这个解决方案它返回了我需要的但没有返回所有应该的信息子数组内部。我从数据库返回了以下行
Array
(
[0] => Array
(
[iSaleID] => 5027347
[userID] => 123
[qty] => 1.0
[price] => 20.00
[item] => Cheese
)
[1] => Array
(
[iSaleID] => 5027347
[userID] => 123
[qty] => 2.0
[price] => 10.00
[item] => Milk
)
我想实现这一点:
Array
(
[0] => Array
(
[iSaleID] => 5027347
[userID] => 123
[items] => Array (
[0] => Array
(
[description] => Cheese
[qty] => 1.0
[price] => 20.00
)
[1] => Array
(
[description] => Milk
[qty] => 2.0
[price] => 10.00
)
)
)
)
...
不确定我的括号是否正确,但我试图创建它,所以我执行了以下操作:
$sql = "storedProcedure";
$query= $con->query($sql);
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$orderCnt = 0;
$groupOrders = array();
$lastSaleID = null;
if(count($results) > 0){
foreach($results as $order){
if($order['iSaleID'] != $lastSaleID ){
$groupOrders[$orderCnt]['id'] = $order['iSaleID'];
$groupOrders[$orderCnt]['userID'] = $order['userID'];
$groupOrders[$orderCnt]['items'][] = array('desc' => $order['desc'], 'qty' => $order['qty'] );
$orderCnt++;
$lastSaleID = $order['iSaleID'];
}
}
}
这将返回 saleID,每个客户只返回一次用户 ID(这是我想要的),但只返回他们订购的第一件商品。我认为这是因为因为 saleID 等于 $lastSaleID 那么它会跳过具有相同销售 ID 的其余行,但是我尝试将$groupOrders[$orderCnt]['items'][] = array('desc' => $order['desc'], 'qty' => $order['qty'] );其放在 IF 语句之外,但这不起作用。有什么建议吗?
梵蒂冈之花