PHP:for-each循环中的数组分组

PHP : Grouping array in for-each loop

本问题已经有最佳答案,请猛点这里访问。

我有一个像这样的数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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"
}

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

1
2
3
4
5
6
7
8
9
10
11
12
array(2) {
 ["currency"]=>
   string(7)"bitcoin"
 ["Totalcs"]=>
   string(1)"1"
}
array(2) {
 ["currency"]=>
   string(8)"ethereum"
 ["Totalcs"]=>
   string(1)"2"
 }

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


创建新数组的简单foreach()将完成此工作:-

1
2
3
4
5
6
7
8
9
10
11
12
$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
2
3
4
5
6
7
8
9
10
11
12
13
$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));

输出:

1
2
3
4
5
6
7
8
9
10
11
12
array (
  0 =>
  array (
    'currency' => 'bitcoin',
    'Totalcs' => '1',
  ),
  1 =>
  array (
    'currency' => 'ethereum',
    'Totalcs' => 2,
  ),
)