Yii model to array?

2019-01-17 06:27发布

How can I convert the result of Trips::model()->findAll() to an array?

标签: arrays model yii
14条回答
看我几分像从前
2楼-- · 2019-01-17 06:39
$model = Trips::model()->findAll(); 
$arr = CHtml::listData($model, 'trip_id', 'trip_name');
var_dump($arr);

CHtml::listData() will return an array value.

查看更多
时光不老,我们不散
3楼-- · 2019-01-17 06:41

You can use this.

$Trips::model()->findAll(array('index'=>'trip_id'));
if(count($Trips)>0)
            {                   
                $TripsArrayList=array();
                foreach($Tripsas as $singleTrip)
                {                   
                    $TripsArrayList[]=array('trip_id'=>$singleTrip->trip_id,'name'=>$singleTrip->name);         
                }                   
            }

Your output will be

Array
    (
      [0] => Array
                 (
                   [trip_id] => 1
                   [name] => Nashik
                 )
      [1] => Array
                 (
                   [trip_id] => 2
                   [name] => Puna
                 ) 
      [2] => Array
                 (
                   [trip_id] => 3
                   [name] => Mumbai
                 ) 
    )
查看更多
放我归山
4楼-- · 2019-01-17 06:41

Use DAO for arrays

$array = Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();
查看更多
祖国的老花朵
5楼-- · 2019-01-17 06:43

Assuming from your question that you want all the attributes, a more compact solution to give you all attributes hashed by id, you can use CActiveRecord's 'attributes' pseudoproperty as follows:

CHtml::listData(Trips::model()->findAll(), 'id', 'attributes')
查看更多
女痞
6楼-- · 2019-01-17 06:43

This is same.

$array = CHtml::listData(Trips::model()->findAll(), 'trip_id', 'trip_name');
查看更多
We Are One
7楼-- · 2019-01-17 06:47

You can create collections CMap continue to work with her

$collections = new CMap();
foreach (YourModel::model()->findAll(['index' => 'id']) as $key => $row) {
   $collections->add($key,$row->attributes);
}
var_dump($collections ->toArray());
查看更多
登录 后发表回答