158

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?

0

14 Answers 14

351

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;
Sign up to request clarification or add additional context in comments.

10 Comments

Why can't we just do $array = json_decode($object,true) ?
@akshaynagpal: It'd result in an error because you'll be giving an object to a function that expects a JSON string as its input. In the answer, I am converting the object to a JSON string, and then feeding it as an input to json_decode() so it would return an array (the second parameter being as True indicates an array should be returned).
i know its too late , but why you not use type casting ... (array) $obj
@NgSekLong: Not really, no.
@chhameed: Typecasting won't work if your object has other objects nested inside it. See example - eval.in/1124950
|
68

Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative.

Take that result and decode with an extra parameter of true, where it will convert to associative array

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

1 Comment

The problem is with values that are not json-encodable or not standardized, ie. dates.
29

Try this:

$new_array = objectToArray($yourObject);

function objectToArray($d) 
{
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return array_map(__FUNCTION__, $d);
    } else {
        // Return array
        return $d;
    }
}

1 Comment

Perfect function to change the stdobject to array
26

You can convert an std object to array like this:

$objectToArray = (array)$object;

2 Comments

This is great, but it converts only the first level. If you have nesting you have to do it for all nodes.
Easy fix it worked
22

There are two simple ways to convert stdClass Object to an Array

$array = get_object_vars($obj);

and other is

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

or you can simply create array using foreach loop

$array = array();
foreach($obj as $key){
    $array[] = $key;
}
print_r($array);

Comments

7

For one-dimensional arrays:

$array = (array)$class; 

For multi-dimensional array:

function stdToArray($obj){
  $reaged = (array)$obj;
  foreach($reaged as $key => &$field){
    if(is_object($field))$field = stdToArray($field);
  }
  return $reaged;
}

2 Comments

Welcome to SO. Would you mind expanding your answer a little to explain how it solves the problem?
For one-dimensional arrays: $array = (array)$class; For multi-dimensional array: code from above
6

While converting a STD class object to array.Cast the object to array by using array function of php.

Try out with following code snippet.

/*** cast the object ***/    
foreach($stdArray as $key => $value)
{
    $stdArray[$key] = (array) $value;
}   
/*** show the results ***/  
print_r( $stdArray );

2 Comments

This will convert the outer object to an array, but if any of the properties are also objects they won't be converted.
As per the OP's question he has one level of object structure. For next levels you have to add another foreach loop.
5
$wpdb->get_results("SELECT ...", ARRAY_A);

ARRAY_A is a "output_type" argument. It can be one of four pre-defined constants (defaults to OBJECT):

OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first columns values as keys (duplicates will be discarded).
ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys.
ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.  

See: http://codex.wordpress.org/Class_Reference/wpdb

1 Comment

this is the only suggested way in WordPress world.
3

You can try this:

$aInitialArray = array_map(function($oObject){
    $aConverted = get_object_vars($oObject);
    return $aConverted['post_id'];
}, $aInitialArray);

Comments

2

if you have an array and array element is stdClass item then this is the solution:

foreach($post_id as $key=>$item){
    $post_id[$key] = (array)$item;
}

now the stdClass has been replaced with an array inside the array as new array element

Comments

1

Using the ArrayObject from Std or building your own

(new \ArrayObject($existingStdClass))

you can use the build in method on the new class:

getArrayCopy()

or pass the new object to

iterator_to_array

1 Comment

If $existingStdClass has a property that is another stdClass then that property remains a stdClass in resulting array. If you need something that works recursively then it seems you need to use the json techniques
1

Lets assume $post_id is array of $item

$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);

strong text

1 Comment

This is more simply accomplished with array_column().
0

I have a function myOrderId($_GET['ID']); which returns multidimensional OBJ. as a String.

None of other 1 liner wokred for me.

This both worked:

$array = (array)json_decode(myOrderId($_GET['ID']), True);

$array = json_decode(json_decode(json_encode(myOrderId($_GET['ID']))), True);

Comments

0

I had a problem with this as my stdClass had stdClasses within them repeatedly. This function recursively converts all elements to an array:

$newArray = objectToArray($oldArray)

function objectToArray($data) {
    // If the element being looked is an object convert to an array
    if(is_object($data)) {
      $data = get_object_vars($data);
    }
    // If the element is an array, iterate though it and call the function again on each item
    if(is_array($data)) {
        foreach($data as $key=>$value){
            $data[$key] = objectToArray($value);
        }
    }
    return $data;
}

3 Comments

This is certainly the long way of doing what the accepted answer achieves in a single line of code.
@mickmackusa Maybe but the accepted answer didn't work for me.
I don't understand how this could be. Perhaps prove that claim with a 3v4l.org demo so that we can see the troublesome data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.