27

My array is like:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => demo1
        )
    [1] => stdClass Object
        (
            [id] => 2
            [name] => demo2
        )
    [2] => stdClass Object
        (
            [id] => 6
            [name] => otherdemo
        )
)

How can I convert the whole array (including objects) to a pure multi-dimensional array?

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Thompson
  • 1,954
  • 10
  • 33
  • 58

7 Answers7

45

Have you tried typecasting?

$array = (array) $object;

There is another trick actually

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

You can have more info here json_decode in the PHP manual, the second parameter is called assoc:

assoc

When TRUE, returned objects will be converted into associative arrays.

Which is exactly what you're looking for.

You may want to try this, too : Convert Object To Array With PHP (phpro.org)

Community
  • 1
  • 1
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
10

Just use this :

json_decode(json_encode($yourArray), true);
Mahdi Shad
  • 1,427
  • 1
  • 14
  • 23
7

You can use array_walk to convert every item from object to array:

function convert(&$item , $key)
{
   $item = (array) $item ;
}

array_walk($array, 'convert');
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Baba
  • 94,024
  • 28
  • 166
  • 217
2

Assuming you want to get to this pure array format:

Array
(
  [1] => "demo1",    
  [2] => "demo2",
  [6] => "otherdemo",
)

Then I would do:

$result = array();
foreach ($array as $object)
{
    $result[$object->id] = $object->name
}

(edit) Actually that's what I was looking for possibly not what the OP was looking for. May be useful to other searchers.

Ade
  • 2,961
  • 4
  • 30
  • 47
1

You should cast all objets, something like :

$result = array();
foreach ($array as $object)
{
    $result[] = (array) $object
}
magnetik
  • 4,351
  • 41
  • 58
1

As you are using OOP, the simplest method would be to pull the code to convert itself into an array to the class itself, you then simply call this method and have the returned array populate your original array.

class MyObject {

    private $myVar;
    private $myInt;

    public function getVarsAsArray() {

        // Return the objects variables in any structure you need
        return array($this->myVar,$this->myInt);

    }

    public function getAnonVars() {

        // If you don't know the variables
        return get_object_vars($this);
    }
}

See: http://www.php.net/manual/en/function.get-object-vars.php for info on get_object_vars()

David Barker
  • 14,484
  • 3
  • 48
  • 77
1

it you have object and you want to set a value as array use

$this->object->pluck('name');

then you get the value as array of names like

["name1", "name2", "name3"];
Alaa Moneam
  • 509
  • 5
  • 10