Combine two arrays

前端 未结 9 622
名媛妹妹
名媛妹妹 2020-11-22 15:47

I have two arrays like this:

array( 
\'11\' => \'11\',
\'22\' => \'22\',
\'33\' => \'33\',
\'44\' => \'44\'
);

array( 
\'44\' => \'44\',
\'55         


        
9条回答
  •  Happy的楠姐
    2020-11-22 15:57

    If you are using PHP 7.4 or above, you can use the spread operator ... as the following examples from the PHP Docs:

    $arr1 = [1, 2, 3];
    $arr2 = [...$arr1]; //[1, 2, 3]
    $arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
    $arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
    $arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]
    
    function getArr() {
      return ['a', 'b'];
    }
    $arr6 = [...getArr(), 'c']; //['a', 'b', 'c']
    
    $arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']
    
    function arrGen() {
        for($i = 11; $i < 15; $i++) {
            yield $i;
        }
    }
    $arr8 = [...arrGen()]; //[11, 12, 13, 14]
    

    It works like in JavaScript ES6.

    See more on https://wiki.php.net/rfc/spread_operator_for_array.

提交回复
热议问题