Home> PHP Framework> YII> body text

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

王林
Release: 2022-10-08 17:08:27
forward
3440 people have browsed it

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);
Copy after login

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; }
Copy after login

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);
Copy after login

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
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!