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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Glen Fletcher
  • 644
  • 5
  • 21
  • 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 Answers3

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

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
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.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

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

Mchl
  • 61,444
  • 9
  • 118
  • 120