php – 按索引累积2D数组
发布时间:2020-12-13 17:02:55 所属栏目:PHP教程 来源:网络整理
导读:我有一个看起来像这样的数组: Array( [0] = Array ( [amount] = 60.00 [store_id] = 1 ) [1] = Array ( [amount] = 40.00 [store_id] = 1 ) [2] = Array ( [amount] = 10.00 [store_id] = 2 )) 将数组减少到总计与store_id相关的’amount’的类似数组的好方
|
我有一个看起来像这样的数组:
Array
(
[0] => Array
(
[amount] => 60.00
[store_id] => 1
)
[1] => Array
(
[amount] => 40.00
[store_id] => 1
)
[2] => Array
(
[amount] => 10.00
[store_id] => 2
)
)
将数组减少到总计与store_id相关的’amount’的类似数组的好方法是什么. 对于实例我想得到这个: Array
(
[0] => Array
(
[amount] => 100.00
[store_id] => 1
)
[2] => Array
(
[amount] => 10.00
[store_id] => 2
)
)
解决方法
要准确再现您的要求:
<?php
$stores = array();
$result = array();
foreach($rows as $i => $entry) {
if (false === ($j = array_search($entry['store'],$stores))) {
$stores[$i] = $entry['store'];
$result[$i] = $entry;
}
else {
$result[$j]['amount'] += $entry['amount'];
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
