【问题标题】:How to merge multiple objects if for loop in Zend Framework 1.12Zend Framework 1.12中for循环如何合并多个对象
【发布时间】:2017-03-31 06:54:07
【问题描述】:

我需要获取属于主要类别及其子类别的所有产品。 控制器部分:

$categories = new Application_Model_DbTable_Categories();

$this->view->children = $categories->fetchAll($categories->select()->where('parent_category = ?', $this->view->category->category_id));

for ($i=0; $i < count($this->view->children); $i++) {
  $this->view->products = $products->fetchAll($products->select()->where('belongs_to_category = ?', $this->view->children[$i]->category_id));
}

然后我想在视图部分显示所有 for 循环,这很容易。 上面的解决方案不能正常工作,因为在每次迭代期间,结果对象都会被新的对象覆盖。

如何在 1 个变量 ($this->view->products) 中连接这些对象?

【问题讨论】:

    标签: php mysql object zend-framework fetch


    【解决方案1】:

    阅读 PHP 手册 ;)

    $data = array();
    
    for ($i=0; $i < count($this->view->children); $i++) {
      $data = $products->fetchAll($products->select()
                       ->where('belongs_to_category = ?', $this->view->children[$i]->category_id);
      $this->view->products = array_merge($this->view->products , $data);
    }
    

    $data = array();
    for ($i=0; $i < count($this->view->children); $i++) {
      $data[] = $this->view->children[$i]->category_id;
    }
    // here some error check - sizeof($data) > 0
    $this->view->products = $products->fetchAll($products->select()
                                     ->where('belongs_to_category IN (?)', implode(',', $data));
    

    【讨论】:

    • 不幸的是,我收到一个错误:警告:array_merge(): Argument #1 is not an array in ...
    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多