Home > Backend Development > PHP Tutorial > How to Convert an stdClass Object to an Array in PHP?

How to Convert an stdClass Object to an Array in PHP?

Mary-Kate Olsen
Release: 2024-11-19 11:07:03
Original
494 people have browsed it

How to Convert an stdClass Object to an Array in PHP?

How to Transform an stdClass Object into an Array in PHP

In PHP, it's possible to encounter instances where an stdClass object is acquired from queries like $wpdb->get_results. To effectively process and manipulate this object, converting it to an array is often necessary.

Here are two practical approaches to achieve this array transformation:

JSON Encoding and Decoding:

The simplest method involves encoding the object as JSON and subsequently decoding the JSON string back into an array:

$array = json_decode(json_encode($object), true);
Copy after login

Manual Traversal:

If preferred, you can manually traverse the object and extract the data into an array:

foreach ($object as $value) {
    $array[] = $value->post_id;
}
Copy after login

This will generate an array of post IDs, which you can easily access and utilize.

The above is the detailed content of How to Convert an stdClass Object to an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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