PHP stdClass to Array and Array to stdClass – stdClass Object

stdClass 和 Array 互换

 

方法一:

function array2object($array) {
 
    if (is_array($array)) {
        $obj = new StdClass();
 
        foreach ($array as $key => $val){
            $obj->$key = $val;
        }
    }
    else { $obj = $array; }
 
    return $obj;
}
 
function object2array($object) {
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
}
 
 
// example:
 
$array = array('foo' => 'bar', 'one' => 'two', 'three' => 'four');
 
$obj = array2object($array);
 
print $obj->one; // output's "two"
 
$arr = object2array($obj);
 
print $arr['foo']; // output's bar

 

方法二:

<?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;
		}
	}
	
	// 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: stdclass, 数组转成对象 

 

 

 

 

 

你可能感兴趣的:(object)