您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關怎么在php中實現數組合并,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
直接將兩個數組的值合并成為一個數組;
$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 )
采用"+"合并數組,如果鍵相同的情況下,前面的數組值會覆蓋掉后面的數組值。
將某個變量放入到另一個數組當中
$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 ) )
通過打印的值可以看出,變量進入數組后,對應的數字索引必然是當前數組中最小的數字索引+1(如果當前數組不存在數字索引,新增元素對應的索引為0)
直接將兩個數組進行合并,兩個數組鍵相同的情況,后面數組的值覆蓋前面數組的值
$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 )
可以看出,兩個數組鍵相同的情況,后面數組的值覆蓋前面數組的值。但是對于數字索引或者數字字符串索引,會按照順序進行重置(第一個數組的第一個數字索引元素從0開始依次填充)
合并數組,遇到相同的鍵將該鍵中值合并為一個子數組
$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中實現數組合并了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。