Kuzey Demirel
Kuzey Demirel

Reputation: 67

Php three array merge combine

$arr1 = array(1,2,3); 
$arr2 = array("a","b","c"); 
$arr3 =array("1a","2b","3c");

How can I do the following ?

print

$one = 1,a,1a
$two = 2,b,2b
$three = 3,c,3c

Upvotes: 0

Views: 60

Answers (3)

Mirceac21
Mirceac21

Reputation: 1754

Try this:

$arr1 = [1,2,3]; 
$arr2 = ["a","b","c"]; 
$arr3 = ["1a","2b","3c"];

$matrix = [$arr1, $arr2, $arr3];

var_dump(transpose($matrix));

function transpose($matrix) {

    return array_reduce($matrix, function($carry, $item) {
        array_walk($item, function ($value, $key) use (&$carry) {
            $carry[$key][] = $value;
        });
        return $carry;
    });
}

Upvotes: 0

Use array_map() function to map through all arrays at the same time. Like this :

$array_merged = array_map(function($v1,$v2,$v3) {
    return $v1 . ','. $v2 . ',' . $v3;
}, $arr1, $arr2, $arr3);
/*
Array (
    [0] => "1,a,1a",
    [1] => "2,b,2b",
    [2] => "3,c,3c",
)
*/

Upvotes: 3

devpro
devpro

Reputation: 16117

You can try this:

$arr1 = array(1,2,3); 
$arr2 = array("a","b","c"); 
$arr3 = array("1a","2b","3c");

$i = 0;
foreach ($arr1 as $key => $value) {
    $newArr[] = $value.",".$arr2[$i].",".$arr3[$i];
$i++;
}
echo implode("<br/>", $newArr);

Result:

1,a,1a
2,b,2b
3,c,3c

You can also perform this by using for loop.

Upvotes: 1

Related Questions