欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php简单对象与数组的转换函数代码(php多层数组和对象的转换)

程序员文章站 2022-12-26 10:55:18
复制代码 代码如下: function arraytoobject($e){ if( gettype($e)!='array' ) return; foreach($e a...
复制代码 代码如下:

function arraytoobject($e){
if( gettype($e)!='array' ) return;
foreach($e as $k=>$v){
if( gettype($v)=='array' || gettype($v)=='object' )
$e[$k]=(object)arraytoobject($v);
}
return (object)$e;
}

function objecttoarray($e){
$e=(array)$e;
foreach($e as $k=>$v){
if( gettype($v)=='resource' ) return;
if( gettype($v)=='object' || gettype($v)=='array' )
$e[$k]=(array)objecttoarray($v);
}
return $e;
}

上面的内容来自 cnblogs jaiho
php多层数组和对象的转换
多层数组和对象转化的用途很简单,便于处理webservice中多层数组和对象的转化
简单的(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);
?>