php - Array sum the same value of element?
Get the solution ↓↓↓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];
}
}
Answer
Solution:
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);
Answer
Solution:
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);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.