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

转载于:https://www.cnblogs.com/imxiu/p/3474367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值