php中stdClass原始类与数组间的互换

2013-10-22 06:05 ·Ab叔 1272 3 <- 点击左侧的数字“攒”一个吧

php程序员或多或少都会接触stdClass,一种原始类。像单一类的时候是很容易与array进行互相转换的。但遇到复杂或多维数组的时候就有点头痛了。

下面介绍复杂的stdClass与多为数组间的互换函数:

1:转换stdClass类到多维数组的方法

function object2arr($d) {
	if (is_object($d)) $d = get_object_vars($d);
	if (is_array($d)) {
		return array_map(__FUNCTION__, $d);
	}
	else {
		return $d;
	}
}
测试
$user = new stdClass;
$user->name = "ab叔";
$user->contacts = new stdClass;
$user->contacts->twitter = "https://twitter.com/qian";
$user->contacts->weibo = "http://weibo.com/encoding";
$user->contacts->homepage = "http://abshu.com";
$user->age = "32";

$array = object2arr($user);
var_dump($array);
返回
array
  'name' => string 'ab叔' (length=4)
  'contacts' => 
    array
      'twitter' => string 'https://twitter.com/qian' (length=24)
      'weibo' => string 'http://weibo.com/encoding' (length=25)
      'homepage' => string 'http://abshu.com' (length=16)
  'age' => string '32' (length=2)

2:转换多维数组到stdClass类的方法

function arr2object($d) {
	if (is_array($d)) {
		return (object) array_map(__FUNCTION__, $d);
	}
	else {
		return $d;
	}
}
测试
$arr = array(
	"name" => "ab叔",
	"contacts" => array(
		"twitter" => "https://twitter.com/qian",
		"weibo" => "http://weibo.com/encoding",
		"homepage" => "http://abshu.com",
	),
	"age" => "32"
);

$obj = arr2object($arr);
var_dump($obj);
返回
object(stdClass)[4]
  public 'name' => string 'ab叔' (length=4)
  public 'contacts' => 
    object(stdClass)[3]
      public 'twitter' => string 'https://twitter.com/qian' (length=24)
      public 'weibo' => string 'http://weibo.com/encoding' (length=25)
      public 'homepage' => string 'http://abshu.com' (length=16)
  public 'age' => string '32' (length=2)