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

How to convert object into array object in php

藏色散人
藏色散人Original
2021-03-18 09:39:332612browse

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;
}

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!

Statement:
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