-1

I have this associative array below:

Array
(
[0] => Array
    (
        [0] => Category
        [1] => fruit
        [2] => carbs
    )

[1] => Array
    (
        [0] => Day 1 - Program
        [1] => Eat banana
        [2] => Eat bread
    )

[2] => Array
    (
        [0] => Day 1 - record
        [1] => 
        [2] =>  
    )

)

each array index relates to the same index in the other arrays. I need to now create 3 arrays by combining the index. The finished array would look like this:

Array 
(
    [0] => Array
    (
        [0] => Category
        [1] => Day 1 - Program
        [2] => Day 1 - record
    )

    [1] => Array
    (
        [0] => fruit
        [1] => Eat banana
        [2] => 
    )

    [2] => Array
    (
        [0] => carbs
        [1] => bread
        [2] =>  
    )
)

The empty slots are where I know to put a textbox to record the data. I've tried nesting for loops and other things but nothing is working. How to combine array into a multidimensional array based on indexes?

Naterade
  • 2,635
  • 8
  • 34
  • 54

3 Answers3

2
$output = call_user_func_array(
    'array_map',
    array_merge(
        array(NULL),
        $input
    )
);

Demo

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

You can achieve this with a nested loop. Loop through the sub-arrays first. On each iteration, loop through the elements in the sub-array, and add them into the result array. The important part here is what we use as the index for the $result array. $index will be the position of the array element in the sub-array. For example, Category would have an index of 0, so it would be pushed to $result[0][].

foreach ($array as $sub) {
    foreach ($sub as $index => $val) {
        $result[$index][] = $val;
    }
}

print_r($result);

Demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • Thank you! I chose yours because the code was shorter. Man, I was on that for 3 hours. – Naterade Apr 24 '14 at 18:23
  • @Naterade: Glad to see you at least tried. Yeah, sometimes you find what you're looking for right away, and sometimes you have to spend hours to get it working. But I'm sure, with experience, you'll be able to solve problems more quickly. Cheers! – Amal Murali Apr 24 '14 at 18:25
1

Here's a quick way - it essentially flips the keys. BTW, the first array you have is an indexed array, not an associative array.

$input = array(
array
    (
    "Category", "fruit", "carbs"
    ),

array
    (
        "Day 1 - Program","Eat banana","Eat bread"
    ),

array
    (
     "Day 1 - record", "", ""
    )

);

foreach ($input as $key => $array){
    foreach ($array as $k => $v){
        $output[$k][$key] = $input[$key][$k];
    }
}

print_r($output);
larsAnders
  • 3,813
  • 1
  • 15
  • 19