0

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!

1
  • I tried it myself using a bunch of nested foreach loops. It was super inefficient and clear that a more elegant method must exist. I did ATTEMPT it myself, thanks. I also went through all the PHP functions but didn't realize that array_combine could work in this context. Commented Aug 15, 2012 at 19:08

2 Answers 2

4

I think array_combine will do the trick:

foreach ($bigarray as &$x) {
  $x = array_combine(array('first_name','last_name','birthday'),$x);
}
Sign up to request clarification or add additional context in comments.

2 Comments

What is the ampersand in ($bigarray as &$x) for?
The ampersand lets us loop through the array by reference so that we can change the array values as we go.
0

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.