How to convert an array to object in PHP?

前端 未结 30 3345
说谎
说谎 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条回答
  •  萌比男神i
    2020-11-22 03:21

    The one I use (it is a class member):

    const MAX_LEVEL = 5; // change it as needed
    
    public function arrayToObject($a, $level=0)
    {
    
        if(!is_array($a)) {
            throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
        }
    
        if($level > self::MAX_LEVEL) {
            throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
        }
    
        $o = new stdClass();
        foreach($a as $key => $value) {
            if(is_array($value)) { // convert value recursively
                $value = $this->arrayToObject($value, $level+1);
            }
            $o->{$key} = $value;
        }
        return $o;
    }
    

提交回复
热议问题