从循环对象中删除项目 [英] Removing an item from object in a loop

查看:62
本文介绍了从循环对象中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组Db结果存储在一个对象中.我需要遍历结果并检查属性(使用另一个数据库查询),然后使用if语句从对象中删除该项目.这是我正在尝试的简化版本:

I have a set of Db results that are stored in an object. I need to loop through the results and check a property (using another DB query) and then use an if statement to remove the item from the object. Here is a simplified version of what I'm attempting:

foreach ($products as $product) {

    if(!$product->active) {
        unset($product);
    }

}
print_r($products);

但是,当我print_r时,项目仍在对象中.我很困惑.

However when I print_r the items are still in the object. I'm getting confused.

推荐答案

那是预期的行为.做你想要的事情有两种主要方法

Thats expected behaviour. There are two main way of doing what you want

foreach ($products as $key => $product) {

    if(!$product->active) {
        unset($products[$key]);
    }

}

第二种方法是使用参考

foreach ($products as &$product) {

    if(!$product->active) {
        unset($product);
    }

}

这篇关于从循环对象中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆