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

How to convert php object to array

藏色散人
藏色散人Original
2020-07-07 10:12:139507browse

How to convert PHP objects into arrays: 1. Use the "json_decode" function to convert the object into a number. The syntax is "json_decode($param, true);"; 2. Use the "object_to_array" method to force the type conversion .

How to convert php object to array

PHP object to array

PHP There are two ways to convert an object into an array:

(1) Use function

$param = json_encode($param);
$param = json_decode($param, true);

This completes the conversion of object-》json-》array

json_decode does not add true and converts json into object

(2) Forced conversion type

function object_to_array($obj) {
    $arr = (array)$obj;
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $arr[$k] = (array)object_to_array($v);
        }
    }
 
    return $arr;
}

For more related knowledge, please visit PHP Chinese website!

The above is the detailed content of How to convert php object to array. 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