Transform object array into only one array

Asked

Viewed 1,471 times

0

I have a array multiples objects:

array(3) {
  [0]=>
  object(stdClass)#5750 (2) {
    ["value"]=>
    string(16) "[email protected]"
    ["key"]=>
    string(18) "email_client"
  }
  [1]=>
  object(stdClass)#5254 (2) {
    ["value"]=>
    string(20) "gold"
    ["key"]=>
    string(19) "package"
  }
  [2]=>
  object(stdClass)#6074 (2) {
    ["value"]=>
    string(5) "senh4"
    ["key"]=>
    string(18) "password"
  }
}

And I need you to stay:

array = {
   email_client => [email protected],
   package => gold,
   password => senha
}

I tried with foreach but it does not access the objects. With the array_walk_recursive the answer is the same. someone can help me?

  • You want to convert Object Array to Indexed Array, with keys?

  • But what I could realize that your question is an object in a way, and an example of output that does not match, the title is one thing and the question speaks in another, could be clearer about the question. and portray your reality, so that you have answers to your reality.

  • I have several objects within an array and each object has an 'Indice'. array{ [0] => object { key : value, value: value} }

  • place this array of objects in your question and the result you want, please?

  • Object(stdClass)#5750 (2) { ["value"]=> string(16) "[email protected]" ["key"]=> string(18) "email_client" } . This is the object. As you can see in the example it has an input in the array.

  • Right @Ivanmoreira, but, the result in your question does not match the keys and join the object array to a single associative array without changing the keys does not give? got it?

  • No? I just want ["key"] => email_client and ["value"] => mail@example of the object to be key/value of my example array email_client => mail@example

Show 2 more comments

2 answers

2


If the array is always the same depth you can do :

$array = array();
foreach ($arr as $obj){

$array[$obj->key] = $array[$obj->value];

}

0

Why not use the objects themselves?

foreach($arr as $obj) {
    echo $obj->key . ': ' . $obj->value; 
}

It is also possible to do cast for array when accessing, if you really want to use array syntax (I don’t see much sense in that):

foreach($arr as $obj) {
    echo (array)$obj['key'] . ': ' . (array)$obj['value']; 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.