I have an array like that :
$my_arr = array();
array(14) {
[0]=>
array(4) {
["id_dde"]=>
string(3) "535"
["id_station"]=>
string(3) "130"
["id_catalog"]=>
string(2) "41"
["quantity"]=>
string(2) "50"
}
[1]=>
array(4) {
["id_dde"]=>
string(3) "535"
["id_station"]=>
string(3) "130"
["id_catalog"]=>
string(3) "259"
["quantity"]=>
string(2) "70"
}
With many indexes like that. My goal is to have a unique value on id_dde, id_station and id_catalog. If I have two indexes with array that have similar values on theses columns, I want to delete one index, and merge both quantity columns. Here is an example :
$my_arr = array();
array(14) {
[0]=>
array(4) {
["id_dde"]=>
string(3) "535"
["id_station"]=>
string(3) "130"
["id_catalog"]=>
string(2) "41"
["quantity"]=>
string(2) "50"
}
[1]=>
array(4) {
["id_dde"]=>
string(3) "535"
["id_station"]=>
string(3) "130"
["id_catalog"]=>
string(3) "41"
["quantity"]=>
string(2) "5"
}
=>
array(14) {
[0]=>
array(4) {
["id_dde"]=>
string(3) "535"
["id_station"]=>
string(3) "130"
["id_catalog"]=>
string(2) "41"
["quantity"]=>
string(2) "55"
}
How can I do that ? I tried with a double foreach and unset but I didn't get the right answer, I guess there is a better method too ?
Thanks!
I got an expect result with double foreach. Try this :
$result=[];
foreach ($my_arr as &$dde1) {
$qty = 0;
foreach ($my_arr as $key => $dde2) {
if ($dde1['id_dde'] == $dde2['id_dde'] && $dde1['id_station'] == $dde2['id_station'] && $dde1['id_catalog'] == $dde2['id_catalog']) {
$qty += $dde2['quantity'];
unset($my_arr[$key]);
}
}
$dde1['quantity'] = $qty;
$result[] = $dde1;
}