dsfsdf5646 2019-05-01 15:13
浏览 763
已采纳

从作为对象元素的数组中删除元素

I'm working on a filter system to filter out food items being displayed on a menu. Every document in the menu collection contains the name of the category (or course if you will) and an array of food items.

I've tried various solutions such as the following code which gets me closer to the desired output.

foreach($menu as $category){

   foreach($category["fooditems"] as $fooditem){

       if ($fooditem["vegetarian"] == false){
                 if (($key = array_search($fooditem, (array) $category["fooditems"])) !== false) 
                    unset($category["fooditems"][$key]);        
    }
  }
}

Before:


{
    "category" : "Starters",
    "fooditems" : [ 
        {
            "name" : "No meat",
            "vegetarian" : true,

        }, 
        {
            "name" : "Horse Meat",
            "vegetarian" : false,
        }, 
        {
            "name" : "Some more meat",
            "vegetarian" : false,
        }
    ]
}

Expected after:


{
    "category" : "Starters",
    "fooditems" : [ 
        {
            "name" : "No meat",
            "vegetarian" : true,

        }
    ]
}

Actual after:


{
    "category" : "Starters",
    "fooditems" : [ 
        {
            "name" : "No meat",
            "vegetarian" : true,

        }, 
        {
            "name" : "Some more meat",
            "vegetarian" : false,
        }
    ]
}

The problem is after it spots a non-vegetarian food item and unsets it, it stops looping. I have no idea why this occurs.

Thank you to anyone who answers :)

  • 写回答

1条回答 默认 最新

  • drbouzlxb92333332 2019-05-01 15:20
    关注

    After decoding the JSON to an array with true you can filter and return only what is equal to true:

    $menu['fooditems'] = array_filter($menu['fooditems'],
                                      function($v) {
                                          return $v['vegetarian'] === true;
                                      });
    

    To use your loop, just track the key and unset using the full path to the array:

    foreach($menu['fooditems'] as $key => $values) {
        if($values['vegetarian'] === false) {
            unset($menu['fooditems'][$key]);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?