Pet*_*ter 36 php object stdclass multidimensional-array
有没有办法在PHP中将多维转换array为stdClass对象?
铸造(object)似乎不会递归地工作. json_decode(json_encode($array))产生我正在寻找的结果,但必须有更好的方法......
Jac*_*kin 58
据我所知,没有预先构建的解决方案,所以你可以自己动手:
function array_to_object($array) {
$obj = new stdClass;
foreach($array as $k => $v) {
if(strlen($k)) {
if(is_array($v)) {
$obj->{$k} = array_to_object($v); //RECURSION
} else {
$obj->{$k} = $v;
}
}
}
return $obj;
}
Run Code Online (Sandbox Code Playgroud)
Ole*_*Ole 40
我知道这个答案来得晚,但我会把它发布给那些正在寻找解决方案的人.
而不是所有这些循环等,您可以使用PHP的本机json_*函数.我有很多方便的功能,我经常使用它
/**
* Convert an array into a stdClass()
*
* @param array $array The array we want to convert
*
* @return object
*/
function arrayToObject($array)
{
// First we convert the array to a json string
$json = json_encode($array);
// The we convert the json string to a stdClass()
$object = json_decode($json);
return $object;
}
/**
* Convert a object to an array
*
* @param object $object The object we want to convert
*
* @return array
*/
function objectToArray($object)
{
// First we convert the object into a json string
$json = json_encode($object);
// Then we convert the json string to an array
$array = json_decode($json, true);
return $array;
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助
您和许多其他人都指出了 JSON 内置函数json_decode()和json_encode(). 您提到的方法有效,但不完全:它不会将索引数组转换为对象,它们将保留为索引数组。但是,有一个技巧可以克服这个问题。您可以使用JSON_FORCE_OBJECT常量:
// Converts an array to an object recursively
$object = json_decode(json_encode($array, JSON_FORCE_OBJECT));
Run Code Online (Sandbox Code Playgroud)
提示:另外,正如这里提到的,您可以使用 JSON 函数递归地将对象转换为数组:
// Converts an object to an array recursively
$array = json_decode(json_encode($object), true));
Run Code Online (Sandbox Code Playgroud)
重要说明:如果您确实关心性能,请不要使用此方法。虽然它简短而干净,但它是替代品中最慢的。请参阅我在此线程中与此相关的其他答案。
function toObject($array) {
$obj = new stdClass();
foreach ($array as $key => $val) {
$obj->$key = is_array($val) ? toObject($val) : $val;
}
return $obj;
}
Run Code Online (Sandbox Code Playgroud)
您可以array_map递归地使用:
public static function _arrayToObject($array) {
return is_array($array) ? (object) array_map([__CLASS__, __METHOD__], $array) : $array;
}
Run Code Online (Sandbox Code Playgroud)
对我来说很完美,因为它不会将例如 Carbon 对象转换为基本的 stdClass(json 编码/解码所做的)