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]);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败