1

I've got an array which looks like this:

array(3) {
  ["title"]=>
  array(3) {
    [0]=>
    string(3) "one"
    [1]=>
    string(3) "two"
    [2]=>
    string(4) "test"
  }
  ["file"]=>
  array(3) {
    [0]=>
    string(25) "company_handbook_2011.pdf"
    [1]=>
    string(8) "test.doc"
    [2]=>
    string(8) "test.doc"
  }
  ["status"]=>
  array(3) {
    [0]=>
    string(4) "SHOW"
    [1]=>
    string(4) "HIDE"
    [2]=>
    string(4) "HIDE"
  }
}

how can i rearrange it to look like this:

array(
    array(
        "one",
        "company_handbook_2011.pdf",
        "SHOW"
    ),
    array(
        "two",
        "test.doc",
        "HIDE"
    ),
    array(
        "test",
        "test.doc",
        "HIDE"
    ),      
)

i.e get the first element of each array and and build a new array and then the second element and so on. Thank very much for your help.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
bharath
  • 1,233
  • 2
  • 11
  • 19
  • There's no ready-made function for this I think. You'll have to simply walk through the array in a loop, and build it – Pekka Apr 07 '11 at 15:41
  • You don't necessarly have to walk through the array since the indexes seem to match between your different keys. You could count the number `$array['title']` and then use a simple for loop that gets the values from the right positions to construct a new array. Would be interesting to benchmark which method is faster. – Capsule Apr 07 '11 at 15:44
  • some useful information from you guys thanks very much...appreciate your time. array_map did the job. – bharath Apr 07 '11 at 15:56

2 Answers2

3

What you are searching for is called the transpose of a matrix. Here is a previous answer on StackOverflow:

Is there better way to transpose a PHP 2D array?

I take the liberty to directly copy the solution from that thread ($array_of_arrays is your original array, $transposed_array is the result):

$transposed_array = call_user_func_array('array_map', array_merge(array(NULL), $array_of_arrays));
Community
  • 1
  • 1
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
0
foreach ($origArray['title'] as $k => $title) {
    $flatArr[] = array($title, $origArray['file'][$k], $origArray['status'][$k]);
}
vartec
  • 131,205
  • 36
  • 218
  • 244