Convert a PHP object to an associative array

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

    Use:

    function readObject($object) {
        $name = get_class ($object);
        $name = str_replace('\\', "\\\\", $name); // Outcomment this line, if you don't use
                                                  // class namespaces approach in your project
        $raw = (array)$object;
    
        $attributes = array();
        foreach ($raw as $attr => $val) {
            $attributes[preg_replace('('.$name.'|\*|)', '', $attr)] = $val;
        }
        return $attributes;
    }
    

    It returns an array without special characters and class names.

提交回复
热议问题