使用yii框架如何遍历使用的2 d数组

时间:2012-06-15 08:14:46

标签: yii

我想得到结果:

parent1 : child1 child1 child1 
parent2 : child2 child2 child2 
parent3 : child3 child3 child3 
parent4 : child4 child4 child4

表名是'category',parent_id=0是Parent类,我想得到每个父亲的孩子。 我使用下面的yii框架是我的代码:

class CtcategoryController extends GtController

{

    public function actionIndex()
    {

        $criteria = new CDbCriteria;
        $criteria -> select = 'id,name';
        $criteria -> limit = 15; 
        $criteria -> condition = 'parent_id = 0';
        $categorys = CtCategory::model()->findAll($criteria);

        foreach($categorys as $category_child){
            $criteria -> condition = 'parent_id = '.$category_child->id;
            $category_child = CtCategory::model()->findAll($criteria);
        }
             //print_r($category_child);==>Aarray()  is null;

        $this->render('index', array(
            'categorys' => $categorys,
        array('category_child' => $category_child)
        ));
    }

1 个答案:

答案 0 :(得分:0)

您需要为第二个查询创建一个新的CDBCriteria,并将结果保存在一个数组中。

class CtcategoryController extends GtController
{
    public function actionIndex()
    {
        $criteria = new CDbCriteria;
        $criteria->select = 'id,name';
        $criteria->limit = 15; 
        $criteria >condition = 'parent_id = 0';
        $categories = CtCategory::model()->findAll($criteria);

        $category_child = array();
        foreach($categories as $key => $category_parent){
            $criteria2 = new CDbCriteria;
            $criteria2->condition = 'parent_id = '.$category_parent->id;
            $category_child[$key] = CtCategory::model()->findAll($criteria2);
        }


        $this->render('index', array(
            'categories' => $categories,
            'category_child' => $category_child,
       ));
    }
}

的index.php

foreach ($categories as $i => $category) :
    echo $category->id;
    foreach (category_child[$i] as $child) :
        echo $child->id;
    endforeach;
endforeach;