Home >Backend Development >PHP Tutorial >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);
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; }
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!