您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)怎么在php中實(shí)現(xiàn)數(shù)組合并,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
直接將兩個(gè)數(shù)組的值合并成為一個(gè)數(shù)組;
$a = [1,2,3,'a'=>'a']; $b = ['a'=>'b',4,5,'b'=>'c',6,7,'a']; $c = $a + $b; print_r($a); print_r($b); print_r($c); //$a Array ( [0] => 1 [1] => 2 [2] => 3 [a] => a ) //$b Array ( [a] => b [0] => 4 [1] => 5 [b] => c [2] => 6 [3] => 7 [4] => a ) //$c Array ( [0] => 1 [1] => 2 [2] => 3 [a] => a [b] => c [3] => 7 [4] => a )
采用"+"合并數(shù)組,如果鍵相同的情況下,前面的數(shù)組值會覆蓋掉后面的數(shù)組值。
將某個(gè)變量放入到另一個(gè)數(shù)組當(dāng)中
$a = [1,'a'=>'aa',2,'b'=>'bb']; $b = [1,'a'=>'aa',2,'b'=>'bb']; print_r($a); print_r($b); array_push($a, $b); print_r($a); //$a Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb ) //$b Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb ) // array_push過后的$a Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb [2] => Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb ) )
通過打印的值可以看出,變量進(jìn)入數(shù)組后,對應(yīng)的數(shù)字索引必然是當(dāng)前數(shù)組中最小的數(shù)字索引+1(如果當(dāng)前數(shù)組不存在數(shù)字索引,新增元素對應(yīng)的索引為0)
直接將兩個(gè)數(shù)組進(jìn)行合并,兩個(gè)數(shù)組鍵相同的情況,后面數(shù)組的值覆蓋前面數(shù)組的值
$a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = [1,'2'=>3,'a'=>'c','b'=>'d','c'=>'e']; $c = array_merge($a,$b); print_r($a); print_r($b); print_r($c); //$a Array ( [0] => 1 [2] => 2 [a] => a [b] => b ) //$b Array ( [0] => 1 [2] => 3 [a] => c [b] => d [c] => e ) //$c Array ( [0] => 1 [1] => 2 [a] => c [b] => d [2] => 1 [3] => 3 [c] => e )
可以看出,兩個(gè)數(shù)組鍵相同的情況,后面數(shù)組的值覆蓋前面數(shù)組的值。但是對于數(shù)字索引或者數(shù)字字符串索引,會按照順序進(jìn)行重置(第一個(gè)數(shù)組的第一個(gè)數(shù)字索引元素從0開始依次填充)
合并數(shù)組,遇到相同的鍵將該鍵中值合并為一個(gè)子數(shù)組
$a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = [1,'2'=>3,'a'=>'a','b'=>'d','c'=>'e']; $c = array_merge_recursive($a,$b); print_r($a); print_r($b); print_r($c); //$a Array ( [0] => 1 [2] => 2 [a] => a [b] => b ) //$b Array ( [0] => 1 [2] => 3 [a] => a [b] => d [c] => e ) //$c Array ( [0] => 1 [1] => 2 [a] => Array ( [0] => a [1] => a ) [b] => Array ( [0] => b [1] => d ) [2] => 1 [3] => 3 [c] => e )
上述就是小編為大家分享的怎么在php中實(shí)現(xiàn)數(shù)組合并了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。