Converting array and objects in array to pure arra

2020-02-10 02:22发布

问题:

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?

回答1:

Have you tried typecasting?

$array = (array) $object;

There is another trick actually

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

See json_encode 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)



回答2:

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

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

array_walk($array, 'convert');


回答3:

Just use this :

json_decode(json_encode($yourArray), true);


回答4:

You should cast all objets, something like :

$result = array();
foreach ($array as $object)
{
    $result[] = (array) $object
}


回答5:

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



回答6:

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.



标签: php arrays