使用Yii 的Active Record 來獲取查詢結果的時候,返回的結果集是一個對象類型的,有時候爲了數據處理的方便但願可以轉成數組返回。好比下面的方法:數組
// 查找知足指定條件的結果中的第一行 $post=Post::model()->find($condition,$params); // 查找具備指定主鍵值的那一行 $post=Post::model()->findByPk($postID,$condition,$params); // 查找具備指定屬性值的行 $post=Post::model()->findByAttributes($attributes,$condition,$params);
返回一條結果的時候直接用 $post->attributes; 就能夠了。app
Post::model()->find()->attributes
若是返回的是多條結果,返回的是一個對象數組的時候有下面3種方法:yii
//第一種直接將結果循環輸出 $trips = Trips::model()->findAll(); $arr = array(); foreach($trips as $t) { $arr[$t->id] = $t->attributes; }
//第二種用array_map $result= array_map(function($record) { return $record->attributes;}, Post::model()->findAllByAttributes($attributes));
或者重寫findAll方法:post
/** * 重寫findALL方法 * @params $condition 查詢條件,$params 參數,$return_array 是否返回數組 * * return 根據條件返回結果類型 */ public function findAll($condition = '',$params=array(), $return_array=false) { $result = CActiveRecord::findAll($condition,$params); if($return_array) { $result = array_map(create_function('$record','return $record->attributes;'),$this->findAll($condition,$params)); } return $result;
}
//第三種方法 $array = CJSON::decode(CJSON::encode($model));
或者使用DAOthis
Use DAO for arraysspa
$array =Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();
其它參考:http://stackoverflow.com/questions/4435886/yii-model-to-arraycode