首页 > 后端开发 > php教程 > PHP 对象和数组的相互转化

PHP 对象和数组的相互转化

WBOY
发布: 2016-07-29 08:56:36
原创
879 人浏览过

对象和数组的相互转化在开发中也是很常见,一般不是多维的情况下直接(array)和(object)就可搞定了,多维的话,遍历下也就可以了:

<code><span><span><?php </span><span>/**
 * 对象和数组的相互转化
 *<span> @link</span> http://www.phpddt.com PHP分享平台
 */</span><span><span>class</span><span>Test</span>{</span><span>public</span><span>$a</span>;
    <span>public</span><span>$b</span>;
    <span>public</span><span><span>function</span><span>__construct</span><span>(<span>$a</span>)</span> {</span><span>$this</span>->a = <span>$a</span>;
    }
}

<span>//对象转数组,使用get_object_vars返回对象属性组成的数组</span><span><span>function</span><span>objectToArray</span><span>(<span>$obj</span>)</span>{</span><span>$arr</span> = is_object(<span>$obj</span>) ? get_object_vars(<span>$obj</span>) : <span>$obj</span>;
    <span>if</span>(is_array(<span>$arr</span>)){
        <span>return</span> array_map(<span>__FUNCTION__</span>, <span>$arr</span>);
    }<span>else</span>{
        <span>return</span><span>$arr</span>;
    }
}

<span>//数组转对象</span><span><span>function</span><span>arrayToObject</span><span>(<span>$arr</span>)</span>{</span><span>if</span>(is_array(<span>$arr</span>)){
        <span>return</span> (object) array_map(<span>__FUNCTION__</span>, <span>$arr</span>);
    }<span>else</span>{
        <span>return</span><span>$arr</span>;
    }
}

<span>$test</span> = <span>new</span> Test(<span>'test1'</span>);
<span>$test</span>->b = <span>new</span> Test(<span>'test2'</span>);

print_r(<span>$test</span>);
<span>$array</span> = objectToArray(<span>$test</span>);
print_r(<span>$array</span>);
<span>$object</span> = arrayToObject(<span>$array</span>);
print_r(<span>$object</span>);</span></span></code>
登录后复制

原文地址。。。

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了PHP 对象和数组的相互转化,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板