Home  >  Article  >  Backend Development  >  PHP对象和数组互转的方法

PHP对象和数组互转的方法

WBOY
WBOYOriginal
2016-06-20 13:04:201139browse

在php开发网站的时候,经常要将两种数据类型相互转化,以便使用。

下面介绍PHP对象和PHP数组将的相互转化方法:

(1)php对象转数组的方法:

<span style="font-size: 14px;">/**</span><br /> * object 转 array<br /> */<br />function object_to_array($obj){<br />$_arr=is_object($obj)?get_object_vars($obj):$obj;<br />foreach($_arr as $key=>$val){<br />$val=(is_array($val))||is_object($val)?object_to_array($val):$val;<br />$arr[$key]=$val;<br />}<br />return $arr;<br /><p>}<span style="font-size: 14px;">

(2)php Json字符转数组的方法:

如果是个 json 字符串的话,可直接通过 json_decode 函数将字符串转换成数组。

json_decode (PHP 5 >= 5.2.0, PECL json >= 1.2.0)json_decode — 接受一个 JSON 格式的字符串并且把它转换为 PHP 变量mixed json_decode(string $json[,bool $assoc])参数:json  待解码的 json string 格式的字符串。

assoc  当该参数为 TRUE 时,将返回一个数组(关联数组)形式的结果,默认为false,返回的是一个对象。


Statement:
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