gpt4 book ai didi

php - 如何根据两个键对数组求和(小计)?

转载 作者:搜寻专家 更新时间:2023-10-31 20:35:50 26 4
gpt4 key购买 nike

我有以下值的数组

 Array
(
[0] => Array
(
[order_date] => 2016-01-01
[sku] => RK101
[qty] => 2
)

[1] => Array
(
[order_date] => 2016-01-01
[sku] => RK101
[qty] => 5
)

[2] => Array
(
[order_date] => 2016-01-01
[sku] => RK102
[qty] => 4
)

[3] => Array
(
[order_date] => 2016-01-02
[sku] => RK101
[qty] => 2
)

[4] => Array
(
[order_date] => 2016-01-02
[sku] => RK101
[qty] => 2
)
)

我想对数组求和,首先按日期,然后按 sku,我想要如下结果

    Array
(
[2016-01-01] => Array
(
[RK101] => Array
(
[qty] => 7
)
[RK102] => Array
(
[qty] => 4
)
)
[2016-01-01] => Array
(
[RK101] => Array
(
[qty] => 4
)
)
)

我探索了堆栈溢出并发现许多帖子基于一个键计算总和,在这种情况下我想先根据日期然后根据 sku 对数组值求和。请帮忙做同样的事情

最佳答案

尝试以下解决方案:

<?php
echo '<pre>';

$array = Array
(
'0' => Array
(
'order_date' => '2016-01-01',
'sku' => 'RK101',
'qty' => 2
),

'1' => Array
(
'order_date' => '2016-01-01',
'sku' => 'RK101',
'qty' => 5
),

'2' => Array
(
'order_date' => '2016-01-01',
'sku' => 'RK102',
'qty' => 4
),

'3' => Array
(
'order_date' => '2016-01-02',
'sku' => 'RK101',
'qty' => 2
),

'4' => Array
(
'order_date' => '2016-01-02',
'sku' => 'RK101',
'qty' => 2
)
);

$new_array = array();
foreach ($array as $a) {
if (!isset($new_array[$a['order_date']][$a['sku']]['qty'])) {
$new_array[$a['order_date']][$a['sku']]['qty'] = 0;
}
$new_array[$a['order_date']][$a['sku']]['qty'] += $a['qty'];
}

print_r($new_array);

输出:

Array
(
[2016-01-01] => Array
(
[RK101] => Array
(
[qty] => 7
)

[RK102] => Array
(
[qty] => 4
)

)

[2016-01-02] => Array
(
[RK101] => Array
(
[qty] => 4
)

)

)

关于php - 如何根据两个键对数组求和(小计)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35270097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com