PHP:根据条件从JSON数组中删除一个元素

问题描述 投票:-1回答:1

我有一个JSON数组。我想删除一个dispatch_quantity = 0的元素。

[{
"order_no": "ORDER123",
"dispatch_quantity": "500",
"balance_quantity": "500"
}, {
"order_no": "ORDER123",
"dispatch_quantity": "0",
"balance_quantity": "500"}]

所以在手术后,输出应该是:

[{
"order_no": "ORDER123",
"dispatch_quantity": "500",
"balance_quantity": "500",
}]    

我试过这个:

foreach ($data as $json_array) { 
  $dispatch_quantity = $json_array['dispatch_quantity']; 
  if ($dispatch_quantity == 0) { 
    unset($json_array[$i]); 
  } 
}       
php arrays json
1个回答
2
投票
$json ='[{
  "order_no": "ORDER123",
  "dispatch_quantity": "500",
  "balance_quantity": "500"
}, {
  "order_no": "ORDER123",
  "dispatch_quantity": "0",
  "balance_quantity": "500"
}]';

$orders = json_decode($json);
$filteredOrders = $orders;
foreach ($filteredOrders as $key => $order)
{
    if ($order->dispatch_quantity == 0)
    {
        unset($filteredOrders[$key]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.