Convert a PHP object to an associative array

后端 未结 30 1509
走了就别回头了
走了就别回头了 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:53

    All other answers posted here are only working with public attributes. Here is one solution that works with JavaBeans-like objects using reflection and getters:

    function entity2array($entity, $recursionDepth = 2) {
        $result = array();
        $class = new ReflectionClass(get_class($entity));
        foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
            $methodName = $method->name;
            if (strpos($methodName, "get") === 0 && strlen($methodName) > 3) {
                $propertyName = lcfirst(substr($methodName, 3));
                $value = $method->invoke($entity);
    
                if (is_object($value)) {
                    if ($recursionDepth > 0) {
                        $result[$propertyName] = $this->entity2array($value, $recursionDepth - 1);
                    }
                    else {
                        $result[$propertyName] = "***";  // Stop recursion
                    }
                }
                else {
                    $result[$propertyName] = $value;
                }
            }
        }
        return $result;
    }
    

提交回复
热议问题