這期內容當中小編將會給大家?guī)碛嘘P怎么在php中實現(xiàn)數(shù)組合并,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
成都創(chuàng)新互聯(lián)IDC提供業(yè)務:成都服務器托管,成都服務器租用,成都服務器托管,重慶服務器租用等四川省內主機托管與主機租用業(yè)務;數(shù)據(jù)中心含:雙線機房,BGP機房,電信機房,移動機房,聯(lián)通機房。
直接將兩個數(shù)組的值合并成為一個數(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ù)組值。
將某個變量放入到另一個數(shù)組當中
$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 ) )
通過打印的值可以看出,變量進入數(shù)組后,對應的數(shù)字索引必然是當前數(shù)組中最小的數(shù)字索引+1(如果當前數(shù)組不存在數(shù)字索引,新增元素對應的索引為0)
直接將兩個數(shù)組進行合并,兩個數(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 )
可以看出,兩個數(shù)組鍵相同的情況,后面數(shù)組的值覆蓋前面數(shù)組的值。但是對于數(shù)字索引或者數(shù)字字符串索引,會按照順序進行重置(第一個數(shù)組的第一個數(shù)字索引元素從0開始依次填充)
合并數(shù)組,遇到相同的鍵將該鍵中值合并為一個子數(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中實現(xiàn)數(shù)組合并了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。