Don P
Don P

Reputation: 63667

PHP add keys to nested arrays

I have nested arrays that do not have keys. I want to add keys in a particular order. What is a clean way to do this?

Start with this array. It is only indexed by position.

[0] => (
    [0] => Tyler
    [1] => Durden
    [2] => 05/07/1985
)
[1] => (
    [0] => Edward
    [1] => Norton
    [2] => 03/21/1988
)

Now apply these keys in order:

['first_name'] =>
['last_name'] =>
['birthday'] =>

Final array:

[0] => (
   ['first_name'] => Tyler
   ['last_name'] => Durden
   ['birthday'] => 05/071985
)
[1] => (
    ['first_name'] => Edward
    ['last_name'] => Norton
    ['birthday'] => 03/21/1988
)

Bonus upvotes if your code allows for any key structure, instead of being hard-coded!

Upvotes: 0

Views: 712

Answers (2)

Stano
Stano

Reputation: 8949

Also the classic algorythm:

foreach ( $array as $key=>$value ) {
   $array[$key]['first_name'] = $array[$key][0];
   $array[$key]['last_name'] = $array[$key][1];
   $array[$key]['birthday'] = $array[$key][2];
   unset($array[$key][0]);
   unset($array[$key][1]);
   unset($array[$key][2]);
}

Upvotes: 0

awm
awm

Reputation: 6570

I think array_combine will do the trick:

foreach ($bigarray as &$x) {
  $x = array_combine(array('first_name','last_name','birthday'),$x);
}

Upvotes: 4

Related Questions