0

I would like to know how to change the contents from several ARRAYS into new ARRAYS. I have this 3 vars with a ARRAY each, lets say the first var is $number and it has this array:

Array
(
    [0] => 1
    [1] => 3
    [2] => 9
)

The second var is $item and it has this:

Array
    (
        [0] => house
        [1] => car
        [2] => bike
    )

And the third is $color and it has this:

Array
    (
        [0] => red
        [1] => white
        [2] => black
    )

How can I change the contents and create new arrays like this:

Array
    (
        [0] => 1
        [1] => house
        [2] => red
    )

Array
    (
        [0] => 3
        [1] => car
        [2] => white
    )

Array
    (
        [0] => 9
        [1] => bike
        [2] => black
    )
Jenz
  • 8,280
  • 7
  • 44
  • 77

2 Answers2

2

You can use array_map:

<?php
$number = [1,3,9];
$item = ['house','car','bike'];
$color = ['red','white','black'];
$res = array_map(null, $number, $item, $color);
print_r($res);
?>

which will output a single array of arrays that you want:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => house
            [2] => red
        )

    [1] => Array
        (
            [0] => 3
            [1] => car
            [2] => white
        )

    [2] => Array
        (
            [0] => 9
            [1] => bike
            [2] => black
        )

)
jh314
  • 27,144
  • 16
  • 62
  • 82
1

You can make a callback function with array_map() that returns each value together:

$result = array();
function merge_arrays($a,$b,$c){
    return array($a,$b,$c); 
}
$result = array_map("merge_arrays",$number,$item,$color);

DEMO

AyB
  • 11,609
  • 4
  • 32
  • 47