Search code examples
phpmultidimensional-arrayformatarray-push

PHP Array_Push with two multidimensional arrays, but keep layout


Using array_push to combine two multidimensional arrays (fruit1, fruit2) but I get results below:

   [86733] => Array
        (
            [Fruit] => Apple
            [NAME] => Mac
        )

    [86734] => Array
        (
            [Fruit] => Orange
            [NAME] => Navel
        )

    [86735] => Array
        (
            [0] => Array
                (
                    [Fruit] => Pear
                    [NAME] => Green
                )

            [1] => Array
                (
                    [Fruit] => Pineapple
                    [NAME] => 
                )
 

Really looking for this kind of format when combining them. Just want to add one array to the other and not merging the arrays.

   [86733] => Array
        (
            [Fruit] => Apple
            [NAME] => Mac
        )

    [86734] => Array
        (
            [Fruit] => Orange
            [NAME] => Navel
        )

    [86735] => Array
        (
             [Fruit] => Pear
             [NAME] => Green
         )

     [86736] => Array
         (
              [Fruit] => Pineapple
              [NAME] => 
          )

Thanks!


Solution

  • So, you don't want to have the new array reindexed?

    You can still use array_push, just use the fact that it is a variadic function which allows you to append multiple arguments:

    array_push($fruit1, ...$fruit2);
    

    Or in syntax backwards compatible for php 5.5 and below:

    call_user_func_array('array_push', array_merge(array(&$fruit1), $fruit2));