phalcon - 循环结果并更改值

时间:2014-05-10 20:15:06

标签: php iterator phalcon

我想遍历所有设置类别,并根据结果设置变量。 所以这样我就可以将更新的数组/对象传递给视图并循环遍历它。 但是我收到了这个错误:

Fatal error: An iterator cannot be used with foreach by reference in  /app/controllers/SettingsController.php on line 9

我的代码:

<?php
class SettingsController extends ControllerBase
{
    public function indexAction()
    {
        $this->tag->prependTitle("settings");
        $settingCategories = SettingCategory::find();
        $this->view->setVar("settingCategories",$settingCategories);
        foreach($settingCategories as &$settingCaterogy){
            if($settingCaterogy->type == "2"){
                $settingCategory->intersection = "deze mag niet";
            }else{
                $settingCategory->intersection = "deze mag";
            }
        }
        $this->view->disable();
        var_dump($settingCategories);
    }
}

当我删除&amp;时,键未定义或编辑

3 个答案:

答案 0 :(得分:0)

删除&amp;来自你的循环迭代器:

foreach($settingCategories as &$settingCaterogy){

foreach($settingCategories as $settingCaterogy){

答案 1 :(得分:0)

我假设你的设置类别是一个对象,这意味着它总是作为参考传递。在这种情况下,您不需要使用&amp;在你的每个陈述中,你也不能,因为你已经发现了。

foreach($settingCategories as $settingCaterogy){
    // …
}

答案 2 :(得分:0)

Bytchek和Teknotica提供的答案是正确的,可以帮助您解决错误。但是,据我所知,phalcon结果集对象是只读的,因此您设置的值不会成功。解决方法是将$ settingCategories对象转换为常规数组,然后循环(通过引用:

$rw = $settingCategories->toArray();
foreach($rw as &$settingCategory){
    if($settingCaterogy["type"] == "2"){
        $settingCategory["intersection"] = "deze mag niet";
    } else {
        $settingCategory->["intersection"] = "deze mag";
    }
}