首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在php中合并具有重复值的多维数组

在php中合并具有重复值的多维数组
EN

Stack Overflow用户
提问于 2018-12-07 03:16:09
回答 1查看 804关注 0票数 0

正如您所看到的,我有一个具有重复orderid的数组,因为一个订单可以有多个stockitems(stockitemname)。我如何合并数组,以便总计字段被求和,orderId不再重复,并且所有的orderId名都放在同一个orderId下?

有没有人有办法解决这个问题?

代码语言:javascript
复制
Array ( [0] => Array 
       ([orderId] => 1544100294 
        [total] => 215.28 
        [receivedate] => 0000-00-00 
        [stockitemname] => "The Gu" red shirt XML tag t-shirt (White) XXS 
        [customerid] => 10 ) 
    [1] => Array 
       ( [orderId] => 1544119651 
        [total] => 37.38 
        [receivedate] => 0000-00-00 
        [stockitemname] => USB rocket launcher (Gray) 
        [customerid] => 10 ) 
    [2] => Array 
        ( [orderId] => 1544100294 
        [total] => 1614.60 
        [receivedate] => 0000-00-00 
        [stockitemname] => Large sized bubblewrap roll 50m 
        [customerid] => 10 ) )

该数组是根据以下查询的结果创建的:

代码语言:javascript
复制
SELECT oc.orderId, SUM(so.quantity*si.RecommendedRetailPrice) total, oc.receivedate, si.stockitemname, ru.customerid
FROM orderbycustomers oc 
JOIN registered_users ru 
ON oc.customerid = ru.customerid 
JOIN stockitemorders so 
ON oc.orderId = so.orderId 
JOIN stockitems si 
ON so.StockItemID = si.StockItemID
WHERE oc.customerid = $customerid
GROUP BY si.stockitemname
ORDER BY oc.receivedate
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-07 05:24:33

另一种方法是在unique array中使用相同的id获取stockitems

代码语言:javascript
复制
<?php

 $input = Array ( Array 
       ('orderId' => '1544100294', 
        'total' => 215.28, 
        'receivedate' => '0000-00-00', 
        'stockitemname' => 'The Gu red shirt XML tag t-shirt (White) XXS', 
        'customerid' => 10 ), 
    Array 
       ( 'orderId' => '1544119651', 
        'total' => 37.38, 
        'receivedate' => '0000-00-00', 
        'stockitemname' => 'USB rocket launcher (Gray)', 
        'customerid' => 10 ),
    Array 
        ( 'orderId' => '1544100294', 
        'total' => 1614.60, 
        'receivedate' => '0000-00-00', 
        'stockitemname' => 'Large sized bubblewrap roll 50m', 
        'customerid' => 10 ) );

 // New array using orderId as the key
 $output = array();

 foreach ($input as $values) {
    // Define your key
    $key = $values['orderId'];
    // Assign to the new array using all of the actual values
    $output[$key][] = $values;
 }

 // Get all values inside the array, but without orderId in the keys:
 $output = array_values($output);

 // Print the new array
 print_r($output);
?>

Here你可以看到它是如何工作的!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53658216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档