I have a array like this how i will get new array
Array
(
[0] => Array
(
[model] => MX555
[color] => RED
[qty] => 2
)
[1] => Array
(
[model] => MX555
[color] => RED
[qty] => 2
)
[2] => Array
(
[model] => MX555
[color] => Green
[qty] => 2
)
[3] => Array
(
[model] => MX555
[color] => Green
[qty] => 1
)
)
I need to return the array like this
Array
(
[0] => Array
(
[model] => MX555
[color] => RED
[qty] => 4
)
[1] => Array
(
[model] => MX555
[color] => Green
[qty] => 4
)
)
I'm assuming you want to identify duplicate items by multiple values, in this case both model
and color
(if you only want to group by the single value color
then see RamC's answer instead). One approach is to create an array, where each key is created by concatenating those values:
function mergeQuantitiesByModelAndColor(array $array)
{
$merged_array = array();
foreach ($array as $item) {
$key = $item['model'] . '|' . $item['color'];
if (!isset($merged_array[$key])) {
$merged_array[$key] = $item;
} else {
$merged_array[$key]['qty'] += $item['qty'];
}
}
return array_values($merged_array);
}
When tested as follows (php 5.6):
$array = array(
array(
'model' => 'MX555',
'color' => 'RED',
'qty' => 2,
),
array(
'model' => 'MX555',
'color' => 'RED',
'qty' => 2,
),
array(
'model' => 'MX555',
'color' => 'Green',
'qty' => 2,
),
array(
'model' => 'MX555',
'color' => 'Green',
'qty' => 1,
),
);
var_dump(mergeQuantitiesByModelAndColor($array));
Gives output:
array(2) {
[0]=>
array(3) {
["model"]=>
string(5) "MX555"
["color"]=>
string(3) "RED"
["qty"]=>
int(4)
}
[1]=>
array(3) {
["model"]=>
string(5) "MX555"
["color"]=>
string(5) "Green"
["qty"]=>
int(3)
}
}
From your question, it is inferable that you want to add the quantity of similar items.
If that is the case, then you can achieve it with the following code snippet.
In the below snippet, I've grouped the items using the element color
.
Feel free to change it as per your requirement.
Snippet
$group_by = 'color';
foreach ($data as $item) {
if (!isset($res[$item[$group_by]])) {
$res[$item[$group_by]] = $item;
} else {
$res[$item[$group_by]]['qty'] += $item['qty'];
}
}
Code
$data = [
[
'model' => "MX555",
'color' => "RED",
'qty' => 2,
],
[
'model' => "MX555",
'color' => "RED",
'qty' => 2,
],
[
'model' => "MX555",
'color' => "Green",
'qty' => 2,
],
[
'model' => "MX555",
'color' => "Green",
'qty' => 1,
],
];
$res = [];
$group_by = 'color';
foreach ($data as $item) {
if (!isset($res[$item[$group_by]])) {
$res[$item[$group_by]] = $item;
} else {
$res[$item[$group_by]]['qty'] += $item['qty'];
}
}
print_r(array_values($res));
Output
Array
(
[0] => Array
(
[model] => MX555
[color] => RED
[qty] => 4
)
[1] => Array
(
[model] => MX555
[color] => Green
[qty] => 3
)
)