maikelsabido
maikelsabido

Reputation: 1327

Combine arrays to form a multidimensional array

I have three arrays:

$arr1 = Array (
    [0] => 1001
    [1] => 1007
    [2] => 1006);

$arr2 = Array (
    [0] => frank
    [1] => youi
    [2] => nashua);

$arr3 = Array (
    [0] => getfrankemail
    [1] => getyouiemail
    [2] => getnashuaemail);

Is there a way to combine these arrays to get a multidimensional array like this:?

Array (
        [0] => Array (
            [0] => 1001
            [1] => frank
            [2] => getfrankemail)
        [1] => Array (
            [0] => 1007
            [1] => youi
            [2] => getyouiemail)
        [2] => Array (
            [0] => 1006
            [1] => nashua
            [2] => getnashuaemail)
        );

Upvotes: 0

Views: 83

Answers (3)

Pete Mitchell
Pete Mitchell

Reputation: 2879

edit: what you are really looking for is a php version of the zip method in ruby/python.

For your specific example array_map works nicely:

$result = array_map(null, $arr1, $arr2, $arr3);

Output:

array (
  0 =>
  array (
    0 => 1001,
    1 => 'frank',
    2 => 'frankemail',
  ),
  1 =>
  array (
    0 => 1007,
    1 => 'youi',
    2 => 'youiemail',
  ),
  2 =>
  array (
    0 => 1006,
    1 => 'nashua',
    2 => 'nashuaemail',
  ),
)

Iterate on the first array (looks like those are ids), and you can match the key for each value to indexes in $arr2 and $arr3

$result = array();

foreach ($arr1 as $key => $value) {
    $result[] = array($value, $arr2[$key], $arr3[$key]);
}

as @kingkero mentions in his answer, you will get errors if they keys do not exist, which you could check for and ignore any rows where that is the case.

$result = array();

foreach ($arr1 as $key => $value) {
    if (!isset($arr2[$key]) || !isset($arr3[$key])) {
        continue;
    }

    $result[] = array($value, $arr2[$key], $arr3[$key]);
}

Upvotes: 3

kero
kero

Reputation: 10638

You can do this with a loop in which you access each of the three arrays with the same key.

$result = array();
$max = count($arr1);
for ($i=0; $i<$max; $i++) {
    $result[] = array(
        $arr1[$i],
        $arr2[$i],
        $arr3[$i],
    );
}

This could fire an out of bounds exception, since it doesn't check whether or not $arrX[$i] exists. Can you be sure that it does?

Upvotes: 0

ilpaijin
ilpaijin

Reputation: 3695

You could use array_push($aContainer, $arr1); or $aContainer[] = $arr[1]

Upvotes: 1

Related Questions