-4

I have an array like this :

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"
}

I want to group this array like this :

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

I tried many ways, but didn't work anyone ....please help me

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Vishnu Gopinath
  • 55
  • 1
  • 10

2 Answers2

2

Simple foreach() with new array creation will do the job:-

$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);

Output:- https://eval.in/957322

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

You will need to assign temporary keys as you iterate your input array. This method will not perform any unnecessary value overwrites.

Code: (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));

Output:

array (
  0 => 
  array (
    'currency' => 'bitcoin',
    'Totalcs' => '1',
  ),
  1 => 
  array (
    'currency' => 'ethereum',
    'Totalcs' => 2,
  ),
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136