153

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?

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Dinesh
  • 4,066
  • 5
  • 21
  • 35

14 Answers14

341

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;
Cesar Bielich
  • 4,754
  • 9
  • 39
  • 81
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • 3
    Why can't we just do `$array = json_decode($object,true)` ? – akshaynagpal Jul 26 '16 at 06:49
  • 4
    @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). – Amal Murali Jul 28 '16 at 19:18
  • 7
    i know its too late , but why you not use type casting ... **(array) $obj** – chhameed Aug 30 '16 at 07:55
  • I found `json_decode(json_encode($object), True)` returned a different array compared to the foreach loop. The foreach loop returns the array in the format OP asked for. – user3442612 Sep 13 '16 at 08:31
  • @user3442612: Shouldn't be different. Care to post a working example on eval.in? – Amal Murali Sep 18 '16 at 18:35
  • The problem with JSON transformation is with values that are not json-encodable or not standardized, ie. dates. – Kangur Sep 10 '18 at 14:50
  • 1
    @NgSekLong: Not really, no. – Amal Murali Dec 28 '18 at 07:22
  • 2
    @chhameed: Typecasting won't work if your object has other objects nested inside it. See example - https://eval.in/1124950 – Amal Murali Jan 04 '20 at 17:27
  • When traversing object manually, how do you access nested values? – Amjad Mar 30 '21 at 22:32
  • What the exact answer is the list of post_ids , here is the change needed ``$array = array_values(json_decode(json_encode($object), true));`` – Nesar Ahmad Nori Feb 14 '23 at 07:37
67

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);
Rey Ramos
  • 689
  • 5
  • 2
27

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;
    }
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
23

You can convert an std object to array like this:

$objectToArray = (array)$object;
JustBaron
  • 2,319
  • 7
  • 25
  • 37
Dinesh Kaswan
  • 369
  • 2
  • 5
21

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);
Tayyab Hayat
  • 815
  • 1
  • 9
  • 22
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;
}
Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
Stack Overflow
  • 189
  • 1
  • 3
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 );
Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
  • This will convert the outer object to an array, but if any of the properties are also objects they won't be converted. – Coleman Jun 15 '19 at 21:24
  • As per the OP's question he has one level of object structure. For next levels you have to add another foreach loop. – Nagama Inamdar Jun 17 '19 at 05:58
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

Vlad
  • 3,626
  • 16
  • 14
3

You can try this:

$aInitialArray = array_map(function($oObject){
    $aConverted = get_object_vars($oObject);
    return $aConverted['post_id'];
}, $aInitialArray);
Sajuna Fernando
  • 1,364
  • 9
  • 16
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

Raptor
  • 53,206
  • 45
  • 230
  • 366
softnwords
  • 11
  • 1
  • 1
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

Decebal
  • 1,376
  • 1
  • 21
  • 36
  • 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 – Patrick May 05 '17 at 15:58
1

Lets assume $post_id is array of $item

$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);

strong text

varun sharma
  • 1,017
  • 15
  • 19
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);
Cyborg
  • 1,437
  • 19
  • 40
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;
}
RGriffiths
  • 5,722
  • 18
  • 72
  • 120