程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> PHP合並數組+號和array_merge的區別

PHP合並數組+號和array_merge的區別

編輯:PHP綜合

PHP的數組融合一般有兩種做法,一種是直接使用加號相加,另一種則是使用array_merge函數進行相加,兩者之間有點區別:

1.相加會證數組中的自然index不被重置
2.相加方法中,被加的數組內的值不會被覆蓋
3.merge函數中的自然index會被重置
4.merge函數,無所謂被merge和merge關系,越後面的array參數,其值,會覆蓋較前面的array參數相同鍵的值

例子:

數組1:

$arr1 = array(
  10 => 'valueof10',
  11 => 'valueof11',
  'key1' => 'dataofkey1',
  'key2' => 'dataofkey2',
  'array' => array(
    'key1' => 1,
    'key2' => 'abc',
    'key3' => array(
      1, 2, 'name' => 'peter'
    ),
  ),
);

數組2:

$arr2 = array(
  10 => 'newvalueof10',
  11 => 'newvalueof11',
  'key1' => 'newdataofkey1',
  'key3' => 'newdataofkey3',
  'array' => array(
    'key1' => 2,
    'key2' => 'defg',
    'key3' => array(
      1, 2, 'name' => 'jonathan', 'gender' => 'male'
    ),
  ),
);

結果比較:

array (size=6)
 10 => string 'valueof10' (length=9)
 11 => string 'valueof11' (length=9)
 'key1' => string 'dataofkey1' (length=10)
 'key2' => string 'dataofkey2' (length=10)
 'array' => 
  array (size=3)
   'key1' => int 1
   'key2' => string 'abc' (length=3)
   'key3' => 
    array (size=3)
     0 => int 1
     1 => int 2
     'name' => string 'peter' (length=5)
 'key3' => string 'newdataofkey3' (length=13)
 
array (size=8)
 0 => string 'valueof10' (length=9)
 1 => string 'valueof11' (length=9)
 'key1' => string 'newdataofkey1' (length=13)
 'key2' => string 'dataofkey2' (length=10)
 'array' => 
  array (size=3)
   'key1' => int 2
   'key2' => string 'defg' (length=4)
   'key3' => 
    array (size=4)
     0 => int 1
     1 => int 2
     'name' => string 'jonathan' (length=8)
     'gender' => string 'male' (length=4)
 2 => string 'newvalueof10' (length=12)
 3 => string 'newvalueof11' (length=12)
 'key3' => string 'newdataofkey3' (length=13)

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved