0

How to sum array the same value of element ?

$arr = [
   ['id' => 1, 'qty' => 100, 'name' => 'a'],
   ['id' => 1, 'qty' => 100, 'name' => 'a'],
   ['id' => 2, 'qty' => 100, 'name' => 'b']
];

become to :

$arr = [
   ['id' => 1, 'qty' => 200, 'name' => 'a'],
   ['id' => 2, 'qty' => 100, 'name' => 'b']
];

i was try but return

[ 1=>['qty'=>200], 2=>['qty'=>100] ]

i was try but return

for($i=0; $i<count($cok);$i++){
        $item_id = $cok[$i]['id'];
        $quantity = $cok[$i]['quantity'];
        if (isset($new_items[$item_id])) {
            $new_items[$item_id] = ['quantity' => $new_items[$item_id]['quantity'] + $quantity];
        } else {
            $new_items[$item_id] = ['quantity' => $quantity];
        }
    }
6
  • Have you tried something ? Commented Sep 14, 2015 at 21:35
  • foreach() loop + basic math Commented Sep 14, 2015 at 21:37
  • You can use a map which stores unique keys Commented Sep 14, 2015 at 21:39
  • 1
    possible duplicate of Associative array, sum values of the same key Commented Sep 14, 2015 at 22:16
  • thats same return with what i try, but different with what i want Commented Sep 14, 2015 at 22:22

2 Answers 2

2

Simple as pie (:

<?php
$arr = array(
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 2, 'qty' => 100, 'name' => 'b')
);

$new_arr = array();
foreach($arr AS $item) {
  if(isset($new_arr[$item['id']])) {
    $new_arr[$item['id']]['qty'] += $item['qty'];
    continue;
  }

  $new_arr[$item['id']] = $item;
}

$arr = array_values($new_arr);

var_dump($arr);
Sign up to request clarification or add additional context in comments.

Comments

0

Dive into my viper

And inplace snippet, returns exactly you need:

<?
$arr = array(
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 2, 'qty' => 100, 'name' => 'b')
);

$ids = array();
foreach ($arr as $i => $subarray) {
    if (!($remove_from_array = array_key_exists($subarray['id'], $ids))) {
        $ids[$subarray['id']] = 0;
    }
    $ids[$subarray['id']] += $subarray['qty'];
    if ($remove_from_array) {
        unset($arr[$i]);
    }
}
foreach ($arr as &$subarray) {
    $subarray['qty'] = $ids[$subarray['id']];
}

print_r($arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.