php数组合并的二种方法_php实例
程序员文章站
2022-04-18 18:43:29
...
我们首先给出两个数组
$r = array(1,2,3,4,5,6);
$e = array(7,8,9,10);
?>
print_r($r+e); // 输出Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
print "
";
print_r(array_merge($r,$e)); // 输出Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 )
?>
$r = array('r'=>1,2,3,4,5,6);
$e = array('r'=>7,8,9,10);
?>
print_r($r+e); // 输出Array ( [r] => 1 [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
print "
";
print_r(array_merge($r,$e)); // 输出Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 )
?>
从这里可以看出,用array_merge合并数组一个数组中的值附加在前一个数组的后面。如果非数字键名相同,则后面数组的值会覆盖前面数组的值。 然而用加号来合并数组如果键名相同,则取最先出现的数组值,后面的就直接忽略掉
复制代码 代码如下:
$r = array(1,2,3,4,5,6);
$e = array(7,8,9,10);
?>
下面我们用array_merge和加号来何必这两数组
复制代码 代码如下:
print_r($r+e); // 输出Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
print "
";
print_r(array_merge($r,$e)); // 输出Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 )
?>
从这里可以看出,用array_merge合并数组一个数组中的值附加在前一个数组的后面。返回作为结果的数组如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。 然而用加号来合并数组如果键名相同,则取最先出现的数组值,后面的就直接忽略掉
下面我们来改变下前面给出的数组
复制代码 代码如下:
$r = array('r'=>1,2,3,4,5,6);
$e = array('r'=>7,8,9,10);
?>
复制代码 代码如下:
print_r($r+e); // 输出Array ( [r] => 1 [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
print "
";
print_r(array_merge($r,$e)); // 输出Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 )
?>
从这里可以看出,用array_merge合并数组一个数组中的值附加在前一个数组的后面。如果非数字键名相同,则后面数组的值会覆盖前面数组的值。 然而用加号来合并数组如果键名相同,则取最先出现的数组值,后面的就直接忽略掉
上一篇: MySQL事件调度器_MySQL