PHP:在for-each循环中对数组进行分组

时间:2018-02-16 07:06:18

标签: php multidimensional-array merge sum

我有一个这样的数组:

array(2) {
  ["currency"]=>
    string(7) "bitcoin"
  ["Totalcs"]=>
   string(1) "1"
}
array(2) {
  ["currency"]=>
    string(8) "ethereum"
  ["Totalcs"]=>
   string(1) "1"
}
array(2) {
  ["currency"]=>
    string(8) "ethereum"
  ["Totalcs"]=>
   string(1) "1"
}

我想像这样对这个数组进行分组:

array(2) {
 ["currency"]=>
   string(7) "bitcoin"
 ["Totalcs"]=>
   string(1) "1"
}
array(2) {
 ["currency"]=>
   string(8) "ethereum"
 ["Totalcs"]=>
   string(1) "2"
 }

我尝试了很多方法,但没有人工作......请帮帮我

2 个答案:

答案 0 :(得分:2)

创建新阵列的简单foreach()将完成这项工作: -

$final_array = [];

foreach($array as $arr){

  $final_array[$arr['currency']]['currency'] = $arr['currency'];
  $final_array[$arr['currency']]['Totalcs'] = (isset($final_array[$arr['currency']]['Totalcs']))? $final_array[$arr['currency']]['Totalcs']+$arr['Totalcs'] : $arr['Totalcs'];

}

$final_array = array_values($final_array);

print_r($final_array);

输出: - https://eval.in/957322

答案 1 :(得分:0)

在迭代输入数组时,需要指定临时键。此方法不会执行任何不必要的值覆盖。

代码:(Demo

$array=[
    ['currency'=>'bitcoin','Totalcs'=>'1'],
    ['currency'=>'ethereum','Totalcs'=>'1'],
    ['currency'=>'ethereum','Totalcs'=>'1']
];
foreach($array as $row){  // iterate all rows
    if(!isset($result[$row['currency']])){  // if first occurrence of currency...
        $result[$row['currency']]=$row;     // save the full row with currency as the temporary key
    }else{                                    // if not the first occurrence of currency...
        $result[$row['currency']]['Totalcs']+=$row['Totalcs'];  // add Totalcs value
    }
}
var_export(array_values($result));

输出:

array (
  0 => 
  array (
    'currency' => 'bitcoin',
    'Totalcs' => '1',
  ),
  1 => 
  array (
    'currency' => 'ethereum',
    'Totalcs' => 2,
  ),
)