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

How to convert php object to array

藏色散人
Release: 2023-03-02 06:52:01
Original
9525 people have browsed it

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);
Copy after login

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;
}
Copy after login

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!

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