array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'function.array-replace.php', 1 => 'array_replace', 2 => 'Replaces elements from passed arrays into the first array', ), 'up' => array ( 0 => 'ref.array.php', 1 => 'Array Funzioni', ), 'prev' => array ( 0 => 'function.array-reduce.php', 1 => 'array_reduce', ), 'next' => array ( 0 => 'function.array-replace-recursive.php', 1 => 'array_replace_recursive', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'reference/array/functions/array-replace.xml', ), 'history' => array ( ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); contributors($setup); ?>
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
array_replace — 使用传递的数组替换第一个数组的元素
array_replace() 创建新数组,并为提供的数组中的每个 key 都分配元素。如果某个 key 出现在多个输入数组中,则将使用最右侧输入数组中的值。
array_replace() 不会递归处理元素项,它在替换时会替换每个 key 的值。
array替换该数组的值。
replacements包含要提取元素的数组。 后面的数组里的值会覆盖前面的值。
返回 array。
示例 #1 array_replace() 示例
<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);
var_dump($basket);
?>以上示例会输出:
array(5) {
[0]=>
string(5) "grape"
[1]=>
string(6) "banana"
[2]=>
string(5) "apple"
[3]=>
string(9) "raspberry"
[4]=>
string(6) "cherry"
}
示例 #2 嵌套数组的处理方式示例
<?php
$base = [ 'citrus' => [ 'orange', 'lemon' ], 'pome' => [ 'apple' ] ];
$replacements = [ 'citrus' => [ 'grapefruit' ] ];
$replacements2 = [ 'citrus' => [ 'kumquat', 'citron' ], 'pome' => [ 'loquat' ] ];
$basket = array_replace($base, $replacements, $replacements2);
var_dump($basket);
?>以上示例会输出:
array(2) {
["citrus"]=>
array(2) {
[0]=>
string(7) "kumquat"
[1]=>
string(6) "citron"
}
["pome"]=>
array(1) {
[0]=>
string(6) "loquat"
}
}