Convert a PHP object to an associative array

后端 未结 30 1533
走了就别回头了
走了就别回头了 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条回答
  •  渐次进展
    2020-11-22 02:41

    If your object properties are public you can do:

    $array =  (array) $object;
    

    If they are private or protected, they will have weird key names on the array. So, in this case you will need the following function:

    function dismount($object) {
        $reflectionClass = new ReflectionClass(get_class($object));
        $array = array();
        foreach ($reflectionClass->getProperties() as $property) {
            $property->setAccessible(true);
            $array[$property->getName()] = $property->getValue($object);
            $property->setAccessible(false);
        }
        return $array;
    }
    

提交回复
热议问题