PHP - recursive Array to Object?

2019-01-23 01:11发布

Is there a way to convert a multidimensional array to a stdClass object in PHP?

Casting as (object) doesn't seem to work recursively. json_decode(json_encode($array)) produces the result I'm looking for, but there has to be a better way...

14条回答
倾城 Initia
2楼-- · 2019-01-23 01:39

As far as I can tell, there is no prebuilt solution for this, so you can just roll your own:

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;
} 
查看更多
Summer. ? 凉城
3楼-- · 2019-01-23 01:49

Here's a function to do an in-place deep array-to-object conversion that uses PHP internal (shallow) array-to-object type casting mechanism. It creates new objects only when necessary, minimizing data duplication.

function toObject($array) {
    foreach ($array as $key=>$value)
        if (is_array($value))
            $array[$key] = toObject($value);
    return (object)$array;
}

Warning - do not use this code if there is a risk of having circular references.

查看更多
干净又极端
4楼-- · 2019-01-23 01:51

You can use the array_map recursively:

public static function _arrayToObject($array) {
    return is_array($array) ? (object) array_map([__CLASS__, __METHOD__], $array) : $array;
}

Works perfect for me since it doesn't cast for example Carbon objects to a basic stdClass (which the json encode/decode does)

查看更多
等我变得足够好
5楼-- · 2019-01-23 01:51
public static function _arrayToObject($array) {
    $json = json_encode($array);
    $object = json_decode($json);
    return $object
}
查看更多
Bombasti
6楼-- · 2019-01-23 01:52

EDIT: This function is conversion from object to array.

From https://forrst.com/posts/PHP_Recursive_Object_to_Array_good_for_handling-0ka

protected function object_to_array($obj)
{
    $arrObj = is_object($obj) ? get_object_vars($obj) : $obj;
    foreach ($arrObj as $key => $val) {
            $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val;
            $arr[$key] = $val;
    }
    return $arr;
}
查看更多
Bombasti
7楼-- · 2019-01-23 01:53

The shortest I could come up with:

array_walk_recursive($obj, function (&$val) { if (is_object($val)) $val = get_object_vars($val); });
查看更多
登录 后发表回答