Created
July 26, 2011 07:08
-
-
Save kijtra/1106169 to your computer and use it in GitHub Desktop.
[PHP] PHPのオブジェクトを配列に変換する関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function obj2arr($obj){ | |
$arr=array(); | |
if(is_object($obj)){ | |
$obj=get_object_vars($obj); | |
}else{ | |
$obj=$obj; | |
} | |
foreach($obj as $key=>$val){ | |
if(is_object($obj[$key])){ | |
$arr[$key]=obj2arr($val); | |
}else if(is_array($val)){ | |
foreach($val as $k=>$v){ | |
if(is_object($v) || is_array($v)){ | |
$arr[$key][$k]=obj2arr($v); | |
}else{ | |
$arr[$key][$k]=$v; | |
} | |
} | |
}else{ | |
$arr[$key]=$val; | |
} | |
} | |
return $arr; | |
} | |
//こっちのほうが軽そうかな? | |
// http://www.php.net/manual/de/language.types.array.php#94241 | |
function object_to_array($mixed){ | |
if(is_object($mixed)){ | |
$mixed=(array)$mixed; | |
} | |
if(is_array($mixed)){ | |
$new=array(); | |
foreach($mixed as $key=>$val){ | |
$key=preg_replace("/^\\0(.*)\\0/","",$key); | |
$new[$key]=object_to_array($val); | |
} | |
}else{ | |
$new=$mixed; | |
} | |
return $new; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment