Make a multidimensional array from 2 or 3 seperate arrays?

I have the following basic arrays: apples, color, and type.

What I want to do is create a single multidimensional array where the values in apples become the keys for the final array and the subsequent arrays which make use of color / type for the key-value pairs. I hope that makes sense!

Example:

"apple1" => array("red"=>"type1"),
"apple2" => array("yellow"=>"type2"),
"apple3" => array("green"=>"type3"),
...

What functions would be best for making this happen?

There are myriad ways of constructing your desired array from those three others. Two that I’ll show here are 1. basic loop and 2. nested array functions.

  1. Basic loop

This just loops over each apple and builds the resulting array one-by-one using the corresponding values from the $color and $type arrays.


$result = array();
foreach ($apples as $key => $apple) {
    $result[$apple] = array($color[$key] => $type[$key]);
}
var_dump($result);

  1. Array functions

This one goes a little crazy by making use of array_combine.


$result = array_combine(
    // keys
    $apples,
    // values
    array_chunk(array_combine($color, $type), 1, TRUE)
);
var_dump($result);

If you need/want any explanation of either code snippet, just ask. (: