如果在 Zend Framework 1.12 中进行循环,如何合并多个对象
How to merge multiple objects if for loop in Zend Framework 1.12
我需要获取属于主要类别及其子类别的所有产品。
控制器部分:
$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));
}
然后我想在view部分用for循环显示all,很简单。
上面的解决方案不能正常工作,因为在每次迭代过程中,结果对象都会被新对象覆盖。
如何将这些对象连接到 1 个变量中($this->view->products)?
先阅读 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));
我需要获取属于主要类别及其子类别的所有产品。 控制器部分:
$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));
}
然后我想在view部分用for循环显示all,很简单。 上面的解决方案不能正常工作,因为在每次迭代过程中,结果对象都会被新对象覆盖。
如何将这些对象连接到 1 个变量中($this->view->products)?
先阅读 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));