I have this array:
["balance"]=>
array(5) {
[0]=>
array(3) {
["balance"]=>
string(4) "0.00"
["id_item"]=>
string(3) "540"
["item"]=>
string(7) "Lampada"
}
[1]=>
array(3) {
["balance"]=>
string(4) "0.00"
["item"]=>
string(6) "Taglio"
["id_item"]=>
string(3) "541"
}
[2]=>
array(3) {
["balance"]=>
string(4) "0.00"
["item"]=>
string(5) "Piega"
["id_item"]=>
string(3) "542"
}
[3]=>
array(3) {
["balance"]=>
string(4) "2.00"
["item"]=>
string(5) "Piega"
["id_item"]=>
string(3) "542"
}
[4]=>
array(3) {
["balance"]=>
string(4) "7.00"
["item"]=>
string(6) "Gelati"
["id_item"]=>
string(3) "543"
}
As you note, there are 2 arrays with a subkey "id_item" == 542. I need remove only the duplicate with a balance == 0. In detail I need remove the key == 2 (because the balance is 0 and there is another item with same ID with balance > 0)
This is my try but I cannot go further:
if ( is_array ( $array['balance'] ) && count ( $array['balance'] ) > 0 ) {
foreach ( $array['balance'] as $key => $value ) {
if ( isset ( $value['id_item'] ) ) {
$id_item = $value['id_item'];
// re-cycle on the array?
// if next id_item == $id_item && value['balance'] == 0.00 remove
}
}
}
I've tried to make it in few lines, check this out:
$array = [
"balance" => [
[
"balance" => "0.00",
"id_item" => "540",
"item" => "Lampada",
],
[
"balance" => "0.00",
"item" => "Taglio",
"id_item" => "541",
],
[
"balance" => "0.00",
"item" => "Piega",
"id_item" => "542",
],
[
"balance" => "2.00",
"item" => "Piega",
"id_item" => "542",
],
[
"balance" => "7.00",
"item" => "Gelati",
"id_item" => "543",
]
]
];
//get array of id_items
$id_items = array_map(function($e) {
return $e['id_item'];
}, $array['balance']);
//get duplicated keys
$duplicated_keys = array_keys(array_filter(array_count_values($id_items), function($v) {
return $v > 1;
}));
//remove duplicated keys where balance is zero
foreach ($array['balance'] as $k => $balance) {
if(in_array($balance['id_item'], $duplicated_keys) && $balance['balance'] == 0) {
unset($array['balance'][$k]);
}
}