Yii Active Record 查詢結果轉化成數組


使用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; 就可以了。

Post::model()->find()->attributes

如果返回的是多條結果,返回的是一個對象數組的時候有下面3種方法:

//第一種直接將結果循環輸出
$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方法:

/**
 * 重寫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));

或者使用DAO

Use DAO for arrays

$array =Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();

其它參考:http://stackoverflow.com/questions/4435886/yii-model-to-array


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM