Home  >  Article  >  PHP Framework  >  How to convert yii objects into arrays or directly output to json format

How to convert yii objects into arrays or directly output to json format

王林
王林forward
2021-01-08 10:13:533534browse

How to convert yii objects into arrays or directly output to json format

How to convert to array?

(Learning video sharing: Programming video)

When we use Yii's Active Record to obtain query results, the returned result set is an object type. If we want to process the data more conveniently, we can convert it into an array and return it, such as the following method:

// 查找满足指定条件的结果中的第一行
$post=Post::model()->find($condition,$params);
// 查找具有指定主键值的那一行
$post=Post::model()->findByPk($postID,$condition,$params);
// 查找具有指定属性值的行
$post=Post::model()->findByAttributes($attributes,$condition,$params);

When returning a result, just use $post->attributes;.

If you want to return the FindAll array, how to deal with it?

There are two methods:

The first is to use a custom function, as follows

/**
 * 简化findall数据
 * */
function simplifyData($data){
	foreach($data as $key=>$val){
		$newData[$key] = $val->attributes;
	}
	return $newData;
}

Then use the function to directly convert the result

The second is It is a very simple method:

$products = ProTuan::model()->findAll($criteria);
$products = json_decode(CJSON::encode($products),TRUE);

The function is to first convert the findAll result into JSON format, and then convert it into an array

As for the conversion of findALL into JOSN format, it is actually using

CJSON::encode

Related recommendations: yii framework

The above is the detailed content of How to convert yii objects into arrays or directly output to json format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete