-1

I'm trying to merge two arrays together, however I can't figure out how.

1st Array:

Array
(
    [0] => a
    [1] => b
    [2] => c
)

2nd Array:

Array
(
    [0] => 1
    [1] => 1
)

What I'm trying to achieve:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => 1
        )

    [1] => Array
        (
            [0] => b
            [1] => 1
        )

    [2] => Array
        (
            [0] => c
        )
)

I know this is very simple to achieve, but my brain refuses to cooperate. Maybe I need more coffee...

// Thanks for all the downvotes :)

Artano
  • 23
  • 2

4 Answers4

2

Simple foreach to iterate:

$a = array('a', 'b', 'c');
$b = array(1, 1);

$result = array();

foreach($a as $key => $value) {
    $tmp = array($value);
    if (isset($b[$key])) {
        $tmp[] = $b[$key];
    }
    $result[] = $tmp;
}

print_r($result);

And result:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => 1
        )

    [1] => Array
        (
            [0] => b
            [1] => 1
        )

    [2] => Array
        (
            [0] => c
        )

)
Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65
2

This is called "zipping" and can be done in php with array_map when the first argument is null:

$x = ['a', 'b', 'c'];
$y = [1, 2];

$z = array_map(null, $x, $y);
print_r($z);

Result:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => 1
        )

    [1] => Array
        (
            [0] => b
            [1] => 2
        )

    [2] => Array
        (
            [0] => c
            [1] => 
        )

)
georg
  • 211,518
  • 52
  • 313
  • 390
0

Maybe not the best way, but it should work in this case:

$newArray = array();
foreach ($array1 as $index => $row) {
    $newArray[$index] = array($row);
    if (isset($array2[$index])) {
        $newArray[$index][] = $array2[$index];
    }
}
Blaatpraat
  • 2,829
  • 11
  • 23
0
//1st Array:
$array_1 = array( 0=>'a',1=>'b',2=>'c');

//2nd Array:
$array_2 = array( 0=>1,1=>1);

//Result:
$holder = array();


for($i =0 ; $i <= max(count($array_1),count($array_2)); $i++){
    if(isset($array_1[$i])){
        $holder[$i][] = $array_1[$i];
    }

    if(isset($array_2[$i])){
        $holder[$i][] = $array_2[$i];
    }
}

//Required Result:
print_r($holder);

Hope this helps...;p

naxrohan
  • 352
  • 3
  • 15