How can I merge PHP arrays?

前端 未结 10 1795
盖世英雄少女心
盖世英雄少女心 2020-12-20 12:43

I have two arrays of animals (for example).

$array = array(
    array(
        \'id\' => 1,
        \'name\' => \'Cat\',
    ),
    array(
        \'id         


        
相关标签:
10条回答
  • 2020-12-20 13:31

    With PHP 5.3 you can do this sort of merge with array_replace_recursive()

    http://www.php.net/manual/en/function.array-replace-recursive.php

    You're resultant array should look like:

    Array (
        [0] => Array
            (
                [id] => 2
                [name] => Cat
                [age] => 321
            )
    
        [1] => Array
            (
                [id] => 1
                [name] => Mouse
                [age] => 123
            )
    )
    

    Which is what I think you wanted as a result.

    0 讨论(0)
  • 2020-12-20 13:34

    @Andy

    http://se.php.net/array_merge

    That was my first thought but it doesn't quite work - however array_merge_recursive might work - too lazy to check right now.

    0 讨论(0)
  • 2020-12-20 13:34
    <?php
          $a = array('a' => '1', 'b' => array('t' => '4', 'g' => array('e' => '8')));
          $b = array('c' => '3', 'b' => array('0' => '4', 'g' => array('h' => '5', 'v' => '9')));
          $c = array_merge_recursive($a, $b);
          print_r($c);
    ?>
    

    array_merge_recursive — Merge two or more arrays recursively

    outputs:

            Array
    (
        [a] => 1
        [b] => Array
            (
                [t] => 4
                [g] => Array
                    (
                        [e] => 8
                        [h] => 5
                        [v] => 9
                    )
    
                [0] => 4
            )
    
        [c] => 3
    )
    
    0 讨论(0)
  • 2020-12-20 13:36

    I would rather prefer array_splice over array_merge because of its performance issues, my solution would be:

    <?php 
    array_splice($array1,count($array1),0,$array2);
    ?>
    
    0 讨论(0)
提交回复
热议问题