Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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... –  deceze Jan 19 '12 at 12:13

3 Answers 3

up vote 0 down vote accepted

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

share|improve this answer

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

share|improve this answer

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.

share|improve this answer
    
Oh, and don't use this in production without 10 pages of documentation on what it does. ;) –  deceze Jan 19 '12 at 12:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.