1

I can't understand how to combine these arrays.

$data = array("a", "b", "c")
$array = array(0 => Array(1 , 2, 3), 1 => Array(4, 5, 6))

I tried different functions such as merge, combine, map..

Result has to be:

 array(
    'a' => array(1, 4),
    'b' => array(2, 5),
    'c' => array(3, 6),
    )
4
  • 2
    Have you tried anything on your own too? Commented Jan 16, 2015 at 18:16
  • Yes of course, i typed loop just need to combined it Commented Jan 16, 2015 at 18:18
  • I cant figure out how Commented Jan 16, 2015 at 18:19
  • 1
    When you try things and they don't work, you should include descriptions of the bad results in your questions here. Commented Jan 16, 2015 at 18:23

2 Answers 2

3

This should work for you:

<?php

    $data = array("a", "b", "c");
    $array = array(array(1 , 2, 3), array(4, 5, 6));

    $result = array();

    foreach($data as $key => $value) {
        foreach($array as $innerKey => $innerValue)
            $result[$value][] = $innerValue[$key];
    }

    print_r($result);

?>

Output:

Array (
    [a] => Array ( [0] => 1 [1] => 4 )
    [b] => Array ( [0] => 2 [1] => 5 )
    [c] => Array ( [0] => 3 [1] => 6 )
)
Sign up to request clarification or add additional context in comments.

Comments

1

A solution that uses the function array_column() available since PHP 5.5:

$data  = array("a", "b", "c");
$array = array(0 => Array(1 , 2, 3), 1 => Array(4, 5, 6));

$result = array();
foreach($data as $i => $v) {
    $result[$v] = array_column($array, $i);
}

If you are stuck with a previous version then use Rizier123's solution (it does the same thing with just a little more code.

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.