获取关键php数组具有相同值的值的总和

时间:2016-06-06 10:04:30

标签: php arrays json

我有以下数组,

Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 ) 

我要发送的内容是JSON格式低于

它将获得一些Equal类别名称,然后将其作为json发送。

[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]

我怎样才能做到这一点? 想要获得foreach循环,然后比较category_name并使用。= +来获得总和?但我输了,

谢谢,

3 个答案:

答案 0 :(得分:3)

尝试以下解决方案:

<?php
$array = array ( 
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);

$new_array = array();
foreach($array as $a){
    if(!isset($new_array[$a['category_name']]['amount'])){
        $new_array[$a['category_name']]['amount'] = 0;
    }
    $new_array[$a['category_name']] = array(
        'category_name' => $a['category_name'],
        'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
    );
}

//print_r(array_values($new_array));

echo json_encode(array_values($new_array));

<强>输出

[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]

答案 1 :(得分:1)

可能的解决方案:

$categoriesArray = array();

foreach ($yourArray as $arrayItem) {
   if (!isset($categoriesArray[$arrayItem['category_name']])) {
       $categoriesArray[$arrayItem['category_name']] = array(
           'category_name' => $arrayItem['category_name'],
           'sum' => 0
       );
   }

   $categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}

$categoriesArray = json_encode(array_values($categoriesArray));

答案 2 :(得分:1)

假设$ input是你的数组,$ output是JSON字符串:

$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
    $categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
    $categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));