Convert a PHP object to an associative array

后端 未结 30 1602
走了就别回头了
走了就别回头了 2020-11-22 02:18

I\'m integrating an API to my website which works with data stored in objects while my code is written using arrays.

I\'d like a quick-and-dirty function to convert

30条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:36

    I use this (needed recursive solution with proper keys):

        /**
         * This method returns the array corresponding to an object, including non public members.
         *
         * If the deep flag is true, is will operate recursively, otherwise (if false) just at the first level.
         *
         * @param object $obj
         * @param bool $deep = true
         * @return array
         * @throws \Exception
         */
        public static function objectToArray(object $obj, bool $deep = true)
        {
            $reflectionClass = new \ReflectionClass(get_class($obj));
            $array = [];
            foreach ($reflectionClass->getProperties() as $property) {
                $property->setAccessible(true);
                $val = $property->getValue($obj);
                if (true === $deep && is_object($val)) {
                    $val = self::objectToArray($val);
                }
                $array[$property->getName()] = $val;
                $property->setAccessible(false);
            }
            return $array;
        }
    

    Example of usage, the following code:

    class AA{
        public $bb = null;
        protected $one = 11;
    
    }
    
    class BB{
        protected $two = 22;
    }
    
    
    $a = new AA();
    $b = new BB();
    $a->bb = $b;
    
    var_dump($a)
    

    Will print this:

    array(2) {
      ["bb"] => array(1) {
        ["two"] => int(22)
      }
      ["one"] => int(11)
    }
    
    

提交回复
热议问题