1

I don't think this can be done (with out my own function), however I'll ask any way.

I have a array in PHP like

array(
  'item1' => array(
               'Hello',
               'Good',
               ),
  'item2' => array(
               'World',
               'Bye',
               ),
  )

The individual fields come from a web form

I want to rearrange it to the following

array(
  array(
    'item1' => 'Hello',
    'item2' => 'World',
     ),
  array(
    'item1' => 'Good',
    'item2' => 'Bye',
     ),
  )

Make an array of objects from the field arrays

I could write a function to do this.

However I was wondering can one of the built-in array functions achieve this for me?

1
  • 1
    No, there is no built-in function that does this particular transformation. You could cobble together a few existing functions though to make them do that... Commented Jan 19, 2012 at 12:13

3 Answers 3

1

There is no built in function to do this - but here is a user-defined one that will:

function convert_array ($array) {
  $result = array();
  foreach ($array as $key => $inner) {
    for ($i = 0; isset($inner[$i]); $i++) {
      $result[$i][$key] = $inner[$i];
    }
  }
  return $result;
}

See it working

Sign up to request clarification or add additional context in comments.

Comments

1

Most certainly not the most efficient, but as close to "one function" as you'll get. ;)

array_map(function ($i) use ($array) { return array_combine(array_keys($array), $i); }, call_user_func_array('array_map', array_merge(array(function () { return func_get_args(); }), $array)));

See http://codepad.viper-7.com/xIn3Oq.

1 Comment

Oh, and don't use this in production without 10 pages of documentation on what it does. ;)
0

No. There is no built in function that would do this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.