我有$test
数组
Array
(
[0] => Array
(
[quantity] => 3
[stock_id] => _PHONE
)
[1] => Array
(
[quantity] => 3
[stock_id] => 102
)
[2] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[3] => Array
(
[quantity] => 3
[stock_id] => 102
)
[4] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[5] => Array
(
[quantity] => 6
[stock_id] => _PHONE
)
[6] => Array
(
[quantity] => 2
[stock_id] => 102
)
)
并将相同的stock_id键加到一个,我使用以下函数:
function sum($array, $key){
isset($array[$key['stock_id']]) ? $array[$key['stock_id']]['quantity'] += $key['quantity'] : $array[$key['stock_id']] = $key;
return $array;
};
//merge same stock_id and sum the quantity same stock id
$sum_same_stock_id = array_reduce($test, "sum");
结果如下:
$ sum_same_stock_id:
Array
(
[_PHONE] => Array
(
[quantity] => 17
[stock_id] => _PHONE
)
[102] => Array
(
[quantity] => 8
[stock_id] => 102
)
)
所以这里的问题是,我想传递一个动态键值而不仅仅是固定值stock_id
&上面quantity
函数中的sum
。尝试了多种方式,但仍然无法找到方法。我们也可以把这些功能放到课堂上吗?
任何建议表示赞赏!
答案 0 :(得分:0)
首先想到的是在数组中再创建两个键,用于存储所需的值。第三个参数包含初始值。像这样:
let!