Search code examples
phparraysmultidimensional-arrayarray-merge

PHP custom array merge on bases of same value and sum of value


I have array like as follow,

Array(
    [0] => Array(
        [account] => 251234567890,
        [price] => 83
    ) [1] => Array(
        [account] => 251234567890,
        [price] => 27
    ) [2] => Array(
        [account] => 251234564526,
        [price] => 180
    ) [3] => Array(
        [account] => 251234567890,
        [price] => 40
    )
)

now with i want to merge array with same account and sum of it's particular price.

I want output array like this,

Array(
    [251234567890] => Array(
        [account] => 251234567890,
        [price] => 150
    ) [251234564526] => Array(
        [account] => 251234564526,
        [price] => 180
    )
)

I have tried like this,

$res = array();
$k = 0;
foreach ($to_account as $vals) {
  if (array_key_exists($vals['account'], $res)) {
    $res[$k]['price'] += $vals['price'];
    $res[$k]['account'] = $vals['account'];
    $k++;
  } else {
    $res[$k] = $vals;
    $k++;
  }
}

As here in input array only two unique account is present so output array should be of that two account with sum of it's price

I have seen something like this in python from here but it want be helpful as it is in python i want it in php i hope someone can help me in this

Thank you


Solution

  • By assigning temporary keys, you can determine whether you are dealing with the first occurrence or not and then use the appropriate technique to either store the whole subarray or merely add value to the price element of the subarray.

    Code: (Demo)

    $to_account = [
      [ 'account' => 251234567890, 'price' => 83 ],
      [ 'account' => 251234567890, 'price' => 27 ],
      [ 'account' => 251234564526, 'price' => 180 ],
      [ 'account' => 251234567890, 'price' => 40 ]
    ];
    
    foreach ($to_account as $row) {
        if (!isset($result[$row['account']])) {
            $result[$row['account']] = $row;
        } else {
            $result[$row['account']]['price'] += $row['price'];
            // imitate the above line if there was another column to sum
        }
    }
    var_export($result);
    

    Output:

    array (
      251234567890 => 
      array (
        'account' => 251234567890,
        'price' => 150,
      ),
      251234564526 => 
      array (
        'account' => 251234564526,
        'price' => 180,
      ),
    )
    

    This method does not bother to overwrite redundant account element values. To reindex the output array, merely call array_values() on it.