Convert stdClass Object to Array in PHP [duplicate]
When working with database results in PHP, it's common to encounter situations where data is retrieved as an object of the stdClass class. While navigating objects can be convenient, sometimes it's necessary to convert them back to arrays.
Consider the scenario where we have retrieved post IDs from the database as follows:
$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
This returns an array of stdClass objects, as shown below:
Array ( [0] => stdClass Object ( [post_id] => 140 ) [1] => stdClass Object ( [post_id] => 141 ) [2] => stdClass Object ( [post_id] => 142 ) )
To convert this array of objects into a simple array of post IDs, we can leverage two approaches:
$array = json_decode(json_encode($post_id), true);
$array = []; foreach ($post_id as $value) $array[] = $value->post_id;
Both methods will produce the desired array:
Array ( [0] => 140 [1] => 141 [2] => 142 )
By utilizing these techniques, you can seamlessly convert stdClass objects into arrays, enabling you to manipulate and process your data as required.
The above is the detailed content of How to Convert stdClass Objects to Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!