Trouble deleting objects from JSON array if it matches a specific condition using PHP. Code is throwing errors

Jason Waltz :

I have this json array I need to loop through and delete all objects that have a stock of 0.

JSON

[
  {
    "products": [
      {
        "title": "cars",
        "stock": 0
      },
      {
        "title": "bike",
        "stock": 2
      },
      {
        "title": "dog",
        "stock": 0
      },
      {
        "title": "cat",
        "stock": 3
      }
    ]
  }
]

So far I have this code below:

<?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));
?>

Here is the run-able snippit: http://sandbox.onlinephpfunctions.com/code/f5d3fb1c98c9cfba7f030c0605e138721bccc937

But I receive only errors:

Warning: Illegal string offset 'stock' in [...][...] on line 6

Warning: Illegal offset type in [...][...] on line 7

I am at a dead end on how to proceed, obviously there is an error with my code but I am not very familiar with how JSON array functions. I need to delete the parent of any item with a stock of zero. Any help would be so much appreciated.

Aksen P :

Your foreach loop has a mistake:

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
        }
    }
}

It should be like:

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]);   
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198942&siteId=1