本文操作环境:windows7系统、php7.1版,dell g3电脑
php的对象转数组
1.
//php stdclass object转array function object_array($array) { if(is_object($array)) { $array = (array)$array; } if(is_array($array)) { foreach($array as $key=>$value) { $array[$key] = object_array($value); } } return $array; }
2.
$array = json_decode(json_encode(simplexml_load_string($xmlstring)),true);
3.
function object2array_pre(&$object) { if (is_object($object)) { $arr = (array)($object); } else { $arr = &$object; } if (is_array($arr)) { foreach($arr as $varname => $varvalue){ $arr[$varname] = $this->object2array($varvalue); } } return $arr;}
4.如果是10w的数据量的话,执行要进1s,结构再复杂些,可以达到3s,性能太差了,可以用以下替换:
function object2array(&$object) { $object = json_decode( json_encode( $object),true); return $object;}
json_decode(json_encode($array),true)
多层数组和对象转化的用途很简单,便于处理webservice中多层数组和对象的转化【推荐学习:《php视频教程》】
简单的(array)和(object)只能处理单层的数据,对于多层的数组和对象转换则无能为力。
通过json_decode(json_encode($object)可以将对象一次性转换为数组,但是object中遇到非utf-8编码的非ascii字符则会出现问题,比如gbk的中文,何况json_encode和decode的性能也值得疑虑。
下面上代码:
<?php function objecttoarray($d) { if (is_object($d)) { // gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * return array converted to object * using __function__ (magic constant) * for recursive call */ return array_map(__function__, $d); } else { // return array return $d; } } function arraytoobject($d) { if (is_array($d)) { /* * return array converted to object * using __function__ (magic constant) * for recursive call */ return (object) array_map(__function__, $d); } else { // return object return $d; } } // useage: // create new stdclass object $init = new stdclass; // add some test data $init->foo = "test data"; $init->bar = new stdclass; $init->bar->baaz = "testing"; $init->bar->fooz = new stdclass; $init->bar->fooz->baz = "testing again"; $init->foox = "just test"; // convert array to object and then object back to array $array = objecttoarray($init); $object = arraytoobject($array); // print objects and array print_r($init); echo "\n"; print_r($array); echo "\n"; print_r($object);?>
以上就是php怎么将对象强制转数组的详细内容。
