1. 程式人生 > 其它 >php多層陣列與物件的轉換 3 種實現方式

php多層陣列與物件的轉換 3 種實現方式

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);