Home > Backend Development > PHP Problem > How to convert object into array object in php

How to convert object into array object in php

藏色散人
Release: 2023-03-08 19:48:01
Original
2748 people have browsed it

php method to convert an object into an array object: first open the corresponding PHP code file; then convert the object into an array through the "function array_to_object($arr){...}" method.

How to convert object into array object in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

php-object (object) and array (array) conversion

Arrays are often used in PHP development. SQL data are all arrays. Arrays and objects are often used and are often converted into each other. Arrays are the soul of PHP and are very powerful. , object-oriented programming is also very convenient.

/**
 * 数组 转 对象
 *
 * @param array $arr 数组
 * @return object
 */
function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
 
    return (object)$arr;
}
 
/**
 * 对象 转 数组
 *
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
 
    return $obj;
}
Copy after login

Recommended learning: "PHP Video Tutorial"

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

Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template