Home > Backend Development > PHP Tutorial > How to Convert stdClass Objects to Arrays in PHP?

How to Convert stdClass Objects to Arrays in PHP?

Barbara Streisand
Release: 2024-11-27 00:43:08
Original
726 people have browsed it

How to Convert stdClass Objects to Arrays in PHP?

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

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
        )

)
Copy after login

To convert this array of objects into a simple array of post IDs, we can leverage two approaches:

  1. JSON Encoding and Decoding: The quickest method is to JSON-encode the object and then decode it back to an array:
$array = json_decode(json_encode($post_id), true);
Copy after login
  1. Manual Traversal: Alternatively, we can traverse the object manually and extract the post IDs:
$array = [];
foreach ($post_id as $value) 
    $array[] = $value->post_id;
Copy after login

Both methods will produce the desired array:

Array
(
    [0]  => 140


    [1] => 141


    [2] => 142

)
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template