Search code examples
phparraysmultidimensional-arrayappendarray-push

Append a 1d array as a new row to a 2d array


I have 2 different arrays with different dimensions that i need to merge in order to get a result with a specific this structure:

the first:

Array
(
    [0] => Array
        (
            [0] => 2017-11-03
            [1] => 2017-11-05
            [2] => 1
        )

    [1] => Array
        (
            [0] => 2017-11-23
            [1] => 2017-11-25
            [2] => 1
        )

)

The second:

Array
(
    [0] => 2017-12-26
    [1] => 2018-01-30
)

The result should be :

Array
    (
        [0] => Array
            (
                [0] => 2017-11-03
                [1] => 2017-11-05
                [2] => 1
            )

        [1] => Array
            (
                [0] => 2017-11-23
                [1] => 2017-11-25
                [2] => 1
            )

        [2] => Array
            (
                [0] =>2017-12-26
                [1] => 2018-01-30
                [2] => 1
            )

    )

I tried using array_merge but it does not work because they have not the same dimension. Also I need an element in the second tab ([2] => 1).


Solution

  • <?php
    
    $array=Array
    (
        0 => Array
        (
            0 => '2017-11-03',
                1 => '2017-11-05',
                2 => '1',
            ),
    
        1 => Array
    (
        0=> '2017-11-23',
                1 => '2017-11-25',
                2 => '1'
            ),
    
    
    );
    
    $arraySmall=Array
    (
        0 => '2017-12-26',
        1 => '2018-01-30'
    );
    
    
    array_push($arraySmall, "1");
    array_push($array, $arraySmall);
    echo'<pre>';
    print_r($array);
    

    And the output is :

    Array
    (
        [0] => Array
            (
                [0] => 2017-11-03
                [1] => 2017-11-05
                [2] => 1
            )
    
        [1] => Array
            (
                [0] => 2017-11-23
                [1] => 2017-11-25
                [2] => 1
            )
    
        [2] => Array
            (
                [0] => 2017-12-26
                [1] => 2018-01-30
                [2] => 1
            )
    
    )
    

    This way can work even without this line array_push($arraySmall, "1"); You can give it a try. In order to "merge" you need same size but for "push" you don't. So if you commend the line i told you the output will look like this:

    Array
    (
        [0] => Array
            (
                [0] => 2017-11-03
                [1] => 2017-11-05
                [2] => 1
            )
    
        [1] => Array
            (
                [0] => 2017-11-23
                [1] => 2017-11-25
                [2] => 1
            )
    
        [2] => Array
            (
                [0] => 2017-12-26
                [1] => 2018-01-30
            )
    
    )