1. 程式人生 > >array_merge可能會踩的坑

array_merge可能會踩的坑

array_merge是很常用的數組合並函式,但是使用時可能會存在一些問題,開發時碰到了,記錄一下

如下程式碼:

$arr = array();
$arr1 = array(
    '100' => 'wmj100',
    '101' => 'wmj101',
    '102' => 'wmj102',
    '103' => 'wmj103',
    '104' => 'wmj104',
);
$arr2 = array(
    '105' => 'wmj105',
    '106' => 'wmj106',
    '107' => 'wmj107',
    '108' => 'wmj108',
    '109' => 'wmj109',
);
$arr3 = array(
    '110' => 'wmj110',
    '111' => 'wmj111',
    '112' => 'wmj112',
    '113' => 'wmj113',
    '114' => 'wmj114',
);

$arr = array_merge($arr1, $arr2, $arr3);
var_dump($arr);

 以上程式碼會輸出:

可以看出陣列的鍵名已經被重置了,這有些時候是不符合我們的需求的,查閱手冊:

 如果是數字索引,array_merge後會重置索引從0開始變為一個新的索引陣列。

 ------------------------------------------------------------------------------------------------------------------------

嘗試關聯陣列:

<?php
$arr = array();
$arr1 = array(
    'skr100'=>'wmj100',
    'skr101'=>'wmj101',
    'skr102'=>'wmj102',
    'skr103'=>'wmj103',
    'skr104'=>'wmj104',
    );
$arr2 = array(
    'skr105'=>'wmj105',
    'skr106'=>'wmj106',
    'skr107'=>'wmj107',
    'skr108'=>'wmj108',
    'skr109'=>'wmj109',
    );
$arr3 = array(
    'skr110'=>'wmj110',
    'skr111'=>'wmj111',
    'skr112'=>'wmj112',
    'skr113'=>'wmj113',
    'skr114'=>'wmj114',
    );
    
    $arr1 = array_merge($arr1,$arr2,$arr3);
var_dump($arr1);

 檢視結果,skr,發現鍵名都保留了

------------------------------------------------------------------------------------------------------------------

那麼如果我們想要得到數字索引的合併結果應該如何做呢?查閱資料得知,php使用陣列相加即可:

<?php

$arr1 = array(
    '100'=>'wmj100',
    '101'=>'wmj101',
    '102'=>'wmj102',
    '103'=>'wmj103',
    '104'=>'wmj104',
    );
$arr2 = array(
    '105'=>'wmj105',
    '106'=>'wmj106',
    '107'=>'wmj107',
    '108'=>'wmj108',
    '109'=>'wmj109',
    );
$arr3 = array(
    '110'=>'wmj110',
    '111'=>'wmj111',
    '112'=>'wmj112',
    '113'=>'wmj113',
    '114'=>'wmj114',
    );
    
    $arr1 = $arr1+$arr2+$arr3;
var_dump($arr1);

執行結果:

因為php弱型別語言的緣故,所以即使使用字串的數字鍵名,使用array_merge也會重置為索引陣列,如果想要得到鍵名不被重置的合併結果,可以使用+,根據需求使用,切不可大意,對程式碼心存敬畏之心。