首页 > 编程语言 > 详细

php多层数组与对象的转换 3 种实现方式

时间:2021-07-17 18:20:10      阅读:17      评论:0      收藏:0      [点我收藏+]

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. 使用 json_decode(json_encode($object),true)

通过json_decode(json_encode($object)可以将对象一次性转换为数组,但是object中遇到非utf-8编码的非ascii字符则会出现问题,比如gbk的中文,何况json_encode和decode的性能也值得疑虑。

3. 相对而言较完美的解决方案:

<?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多层数组与对象的转换 3 种实现方式

原文:https://www.cnblogs.com/ruiyao18369/p/15023800.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!