[php] Convert stdClass object to array in 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?

This question is related to php arrays

The answer is


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;
    }
}

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


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


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);

You can convert an std object to array like this:

$objectToArray = (array)$object;

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);

You can try this:

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

Lets assume $post_id is array of $item

$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);

strong text


$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


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;
}

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);

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 );