我有这个数组:
["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"
}
正如您所注意到的,有2个数组带有子键“id_item”== 542.我只需要删除余数为== 0的副本。详细说明我需要删除键== 2(因为余额为0)并且还有另一个具有相同ID的项目,其余为> 0)
这是我的尝试,但我不能走得更远:
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
}
}
}
答案 0 :(得分:1)
我试过几行,检查一下:
$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]);
}
}