Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert stdClass object to array in PHP

Tags:

arrays

php

I fetch post_id from postmeta as:

$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");

when i try print_r($post_id); I have array like this:

Array
(
    [0] => stdClass Object
        (
            [post_id] => 140
        )

    [1] => stdClass Object
        (
            [post_id] => 141
        )

    [2] => stdClass Object
        (
            [post_id] => 142
        )

)

and i dont know how to traverse it, and how could I get array like this

Array
(
    [0]  => 140


    [1] => 141


    [2] => 142

)

Any idea how can I do this?

like image 767
Dinesh Avatar asked Oct 03 '22 02:10

Dinesh


People also ask

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.

How do I print a stdClass object?

If you just want to print you can use var_dump() or print_r() . var_dump($obj); print_r($obj); If you want an array of all properties and their values use get_object_vars() .


1 Answers

The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), true);

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) 
    $array[] = $value->post_id;
like image 320
Amal Murali Avatar answered Oct 17 '22 16:10

Amal Murali