Home > Backend Development > PHP Tutorial > Conversion between PHP objects and arrays

Conversion between PHP objects and arrays

WBOY
Release: 2016-07-29 08:56:36
Original
883 people have browsed it

The mutual conversion of objects and arrays is also very common in development. Generally, if it is not multi-dimensional, it can be done directly (array) and (object). If it is multi-dimensional, it can be done by traversing:

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

Original address. . .

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

The above introduces the mutual conversion of PHP objects and arrays, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template