Convert stdClass object to array in PHP

PhpArrays

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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;

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

You can convert an std object to array like this:

$objectToArray = (array)$object;

Solution 5 - Php

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

Solution 6 - Php

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

Solution 7 - Php

$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

Solution 8 - Php

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

Solution 9 - Php

You can try this:

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

Solution 10 - Php

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

Solution 11 - Php

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

Solution 12 - Php

Lets assume $post_id is array of $item

$post_id = array_map(function($item){
        
       return $item->{'post_id'};
    	
       },$post_id);

strong text

Solution 13 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDineshView Question on Stackoverflow
Solution 1 - PhpAmal MuraliView Answer on Stackoverflow
Solution 2 - PhpRey RamosView Answer on Stackoverflow
Solution 3 - PhpAlessandro MinoccheriView Answer on Stackoverflow
Solution 4 - PhpDinesh KaswanView Answer on Stackoverflow
Solution 5 - PhpTayyab HayatView Answer on Stackoverflow
Solution 6 - PhpStack OverflowView Answer on Stackoverflow
Solution 7 - PhpVladView Answer on Stackoverflow
Solution 8 - PhpNagama InamdarView Answer on Stackoverflow
Solution 9 - PhpSajuna FernandoView Answer on Stackoverflow
Solution 10 - PhpsoftnwordsView Answer on Stackoverflow
Solution 11 - PhpDecebalView Answer on Stackoverflow
Solution 12 - Phpvarun sharmaView Answer on Stackoverflow
Solution 13 - PhpCyborgView Answer on Stackoverflow