How to convert php array to object

藏色散人
Release: 2023-03-02 17:22:01
Original
3275 people have browsed it

The way to convert a php array into an object is to convert it directly by creating a new anonymous class. The specific statement is "protected function arrayTransitionObject(Array $array) {if (is_array($array)) }".

How to convert php array to object

php array conversion object method

Although php cannot directly new Object like js, php supports anonymous classes We can just create a new anonymous class for conversion

  /**
     * 数组转对象
     * @param Array $array
     * @author Quan
     * @return Object
     */
    protected function arrayTransitionObject(Array $array) 
    {
        if (is_array($array)) {
            $obj = new class{};
            foreach ($array as $key => $val) {
                $obj->$key = $val;
            }
        } else {
            $obj = $array;
        }
        return $obj;
    }
Copy after login

Recommended: "PHP Tutorial"

The above is the detailed content of How to convert php array to object. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template