php - How to sum value of array if some values are same? -
i have following array
array ( [0] => 1995,17500 [1] => 2052,17500 [2] => 2052,17500 [3] => 2236,30000 [4] => 2235,15000 [5] => 2235,40000 );
i have exploded value comma ,.
foreach($array $key=>$value) { $newar = explode(',', $value); }
so have similar first value i.e $newar["0"]. example 2235 , 2052. , have sum of second value i.e $newar["1"].
how can achieve following result php.
array ( [0] => 1995, 17500 [1] => 2052, 35000 [2] => 2036, 30000 [3] => 2235, 55000 )
you can create new array key/index based , use array_key_exists
check if key exists. if sum value, if not create key. not exact result want, it's neater.
$newar = []; //new array foreach($array $value) { $explarr = explode(',', $value); if(array_key_exists($explarr[0], $newar)){ //check if key exists $newar[$explarr[0]] += $explarr[1]; //sum value existing key } else { $newar[$explarr[0]] = $explarr[1]; //create key } }
your result array this:
array ( [1995] => 17500 [2052] => 35000 [2036] => 30000 [2235] => 55000 )
Comments
Post a Comment