Rumah >pembangunan bahagian belakang >tutorial php >PHP 对象和数组的相互转化

PHP 对象和数组的相互转化

WBOY
WBOYasal
2016-07-29 08:56:36889semak imbas

对象和数组的相互转化在开发中也是很常见,一般不是多维的情况下直接(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教程有兴趣的朋友有所帮助。

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn