PHP中array_merge合并兩個數組的程式_PHP教程

來源:互聯網
上載者:User
合并資料在php中我們利用array_merge()函數來實現,array_merge() 函數把兩個或多個數組合并為一個數組。如果鍵名有重複,該鍵的索引值為最後一個鍵名對應的值(後面的覆蓋前面的)。如果數組是數字索引的,則鍵名會以連續方式重新索引。
代碼如下 複製代碼


echo "rn第一種情況rn";
$a=array(1,2,3,4,5,6);
$b=array(7,8,9);

$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);


echo "rn第二種情況rn";
$a=array('a','b','c','d','e','f');
$b=array('a','x','y');

$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);


echo "rn第三種情況rn";

$a=array(
1=>'a',
2=>'b',
3=>'c',
4=>'d',
5=>'e',
6=>'f');
$b=array(
1=>'a',
7=>'x',
8=>'y');

$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);
?>

結果如下:

第一種情況
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Array
(
[0] => 7
[1] => 8
[2] => 9
[3] => 4
[4] => 5
[5] => 6
)

第二種情況
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => a
[7] => x
[8] => y
)
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
Array
(
[0] => a
[1] => x
[2] => y
[3] => d
[4] => e
[5] => f
)

第三種情況
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => a
[7] => x
[8] => y
)
Array
(
[1] => a
[2] => b
[3] => c
[4] => d
[5] => e
[6] => f
[7] => x
[8] => y
)
Array
(
[1] => a
[7] => x
[8] => y
[2] => b
[3] => c
[4] => d
[5] => e
[6] => f
)

1)鍵名

為數字時,array_merge()不會覆蓋掉原來的值,但+合并數組則會把最先出現的值作為最終結果返回,而把後面的數組擁有相同鍵名的那些值“拋棄”掉(不是覆蓋)

2)鍵名為字元時,+仍然把最先出現的值作為最終結果返回,而把後面的數組擁有相同鍵名的那些值“拋棄”掉,但array_merge()此時會覆蓋掉前面相同鍵名的值


注釋:如果僅僅向 array_merge() 函數輸入了一個數組,且鍵名是整數,則該函數將返回帶有整數鍵名的新數組,其鍵名以 0 開始進行重新索引

http://www.bkjia.com/PHPjc/628937.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/628937.htmlTechArticle合并資料在php中我們利用array_merge()函數來實現,array_merge() 函數把兩個或多個數組合并為一個數組。如果鍵名有重複,該鍵的索引值為最後一...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.