0

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)
        );
0

3 Answers 3

3

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]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This would get OP [ [1001,1007,1006], [frank, youi, nashua], [frankemail, youiemail, nashuaemail] ] which is not the wanted result
@kingkero I have edited my answer with a slightly different approach ;)
@PeteMitchell Wow this solution is perfect. It solved my problem. Thanks! :)
1

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

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.