使用PHP从JSON数组中删除符合特定条件的对象时出现问题。代码正在抛出错误

使用PHP从JSON数组中删除符合特定条件的对象时出现问题。代码正在抛出错误,php,json,Php,Json,我有一个json数组,需要循环并删除所有库存为0的对象 JSON 到目前为止,我有以下代码: <?php $str = '[{"products":[{"title":"cars","stock":0},{"title":"bike","stock":2},{"title":"dog","stock":0},{"title":"cat","stock":3}]}]'; $json_decoded = json_decode($str,true); foreach($json_decoded

我有一个json数组,需要循环并删除所有库存为0的对象

JSON

到目前为止,我有以下代码:

<?php
$str = '[{"products":[{"title":"cars","stock":0},{"title":"bike","stock":2},{"title":"dog","stock":0},{"title":"cat","stock":3}]}]';
$json_decoded = json_decode($str,true);
foreach($json_decoded as $index){
    foreach(['products'] as $product_index => $product_data){
        if($product_data['stock'] == 0){
            unset($json_decoded[$index]['products'][$product_index]);
        }
    }
}
echo json_encode($json_decoded));
?>

我在如何继续的问题上走到了死胡同,显然我的代码中有一个错误,但我对JSON数组的功能不是很熟悉。我需要删除库存为零的任何项目的父项。任何帮助都将不胜感激

您的foreach循环有一个错误:

foreach($json_decoded as $index){                                 //<---- here
    foreach(['products'] as $product_index => $product_data){     //<---- here
        if($product_data['stock'] == 0){
            unset($json_decoded[$index]['products'][$product_index]);   //<---- and here
        }
    }
}

请尝试以下较短的版本:

foreach(array_keys(array_column($json_decoded[0]["products"],"stock"),0) as $no_stock){
    unset($json_decoded[0]["products"][$no_stock]);
};

演示:

分析错误:语法错误,意外“'),应为“;”或者,“,”
echo json_encode($json_decoded))中
非常感谢您帮助我理解了这一点。不客气,不要忘记在调试过程中的每一步都使用
print\r()
,它可能会帮助您了解正在操作的数据类型
foreach($json_decoded as $index){                                 //<---- here
    foreach(['products'] as $product_index => $product_data){     //<---- here
        if($product_data['stock'] == 0){
            unset($json_decoded[$index]['products'][$product_index]);   //<---- and here
        }
    }
}
foreach($json_decoded as $ind=>$data){ 
    foreach($data['products'] as $product_index => $product_data){  
        if($product_data['stock'] == 0){
            unset($json_decoded[$ind]['products'][$product_index]);   
        }
    }
}
foreach(array_keys(array_column($json_decoded[0]["products"],"stock"),0) as $no_stock){
    unset($json_decoded[0]["products"][$no_stock]);
};