我有一组存储在对象中的Db结果.我需要遍历结果并检查属性(使用另一个数据库查询),然后使用if语句从对象中删除项目.这是我正在尝试的简化版本:
foreach ($products as $product) {
if(!$product->active) {
unset($product);
}
}
print_r($products);
Run Code Online (Sandbox Code Playgroud)
但是当我print_r时,项目仍在对象中.我很困惑.
rea*_*dow 16
这是预期的行为.做你想做的事有两种主要方式
foreach ($products as $key => $product) {
if(!$product->active) {
unset($products[$key]);
}
}
Run Code Online (Sandbox Code Playgroud)
第二种方式是使用参考
foreach ($products as &$product) {
if(!$product->active) {
unset($product);
}
}
Run Code Online (Sandbox Code Playgroud)