How to convert an array to object in PHP?

前端 未结 30 2814
说谎
说谎 2020-11-22 02:48

How can I convert an array like this to an object?

[128] => Array
    (
        [status] => "Figure A.
 Facebook\'s horizontal scrollbars showing u         


        
30条回答
  •  名媛妹妹
    2020-11-22 03:13

    Inspired by all these codes, i tried to create a enhanced version with support to: specific class name, avoid constructor method, 'beans' pattern and strict mode (set only existing properties):

        class Util {
    
    static function arrayToObject($array, $class = 'stdClass', $strict = false) {
            if (!is_array($array)) {
                return $array;
            }
    
            //create an instance of an class without calling class's constructor
            $object = unserialize(
                    sprintf(
                            'O:%d:"%s":0:{}', strlen($class), $class
                    )
            );
    
            if (is_array($array) && count($array) > 0) {
                foreach ($array as $name => $value) {
                    $name = strtolower(trim($name));
                    if (!empty($name)) {
    
                        if(method_exists($object, 'set'.$name)){
                            $object->{'set'.$name}(Util::arrayToObject($value));
                        }else{
                            if(($strict)){
    
                                if(property_exists($class, $name)){
    
                                    $object->$name = Util::arrayToObject($value); 
    
                                }
    
                            }else{
                                $object->$name = Util::arrayToObject($value); 
                            }
    
                        }
    
                    }
                }
                return $object;
            } else {
                return FALSE;
            }
            }
    }
    

提交回复
热议问题