百科狗-知识改变命运!
--

array_replace() - 使用传递的数组替换第一个数组的元素 - php 数组函数

梵高1年前 (2023-11-21)阅读数 21#技术干货
文章标签数组

array_replace()

(PHP 5 >= 5.3.0, PHP 7)

使用传递的数组替换第一个数组的元素

说明

array_replace(array $array1[,array $...]): array

array_replace()函数使用后面数组元素相同 key 的值替换$array1数组的值。如果一个键存在于第一个数组同时也存在于第二个数组,它的值将被第二个数组中的值替换。如果一个键存在于第二个数组,但是不存在于第一个数组,则会在第一个数组中创建这个元素。如果一个键仅存在于第一个数组,它将保持不变。如果传递了多个替换数组,它们将被按顺序依次处理,后面的数组将覆盖之前的值。

array_replace()是非递归的:它将第一个数组的值进行替换而不管第二个数组中是什么类型。

参数

$array1

替换该数组的值。

包含要提取元素的数组。后面的数组里的值会覆盖前面的值。

返回值

返回一个数组。如果发生错误,将返回NULL

范例

Example #1array_replace()范例

array_replace() - 使用传递的数组替换第一个数组的元素 - php 数组函数

以上例程会输出:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

参见

  • array_replace_recursive() 使用传递的数组递归替换第一个数组的元素
  • array_merge() 合并一个或多个数组
If the arrays are associative (that is, their keys are strings), then I believe this function is identical to (the older) array_merge.
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.
 
/**
 * @param array $array
 * @param array $replacements
 * @param boolean $override
 * @return array
 */
function array_replace_keys(array $array, array $replacements, $override = false) {
  foreach ($replacements as $old => $new) {
    if(is_int($new) || is_string($new)){
      if(array_key_exists($old, $array)){
        if(array_key_exists($new, $array) && $override === false){
          continue;
        }
        $array[$new] = $array[$old];
        unset($array[$old]);
      }
    }
  }
  return $array;
}
In some cases you might have a structured array from the database and one
of its nodes goes like this;

Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following

I hope that this will save someone's time.
You can also use:

RESULT:
Array
(
  [0] => NO-Orange
  [572] => BANANAPHONE!!!
  [omg] => NO-Chili
  [nevermind] => mango
)
with regards
I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );
$array2 = array( "food" => "wine");
$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
 
This is will replace the value for "food" for "dewberry" with "wine".
The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.
I hope this helps atleast one person for all that I've gained from this site.
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

Check on this code:

Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...
Here is a simple array_replace_keys function:
/**
   * This function replaces the keys of an associate array by those supplied in the keys array
   *
   * @param $array target associative array in which the keys are intended to be replaced
   * @param $keys associate array where search key => replace by key, for replacing respective keys
   * @return array with replaced keys
   */
  private function array_replace_keys($array, $keys)
  {
    foreach ($keys as $search => $replace) {
      if ( isset($array[$search])) {
        $array[$replace] = $array[$search];
        unset($array[$search]);
      }
    }
    return $array;
  }
// Test Drive
print_r(array_replace_keys(['one'=>'apple', 'two'=>'orange'], ['one'=>'ett', 'two'=>'tvo']);
// Output
array(
'ett'=>'apple',
'tvo'=>'orange'
)
The documentation is wrongly phrased: "array_replace() replaces the values of array1" No replacing is done. A new array is created which looks like the one that would have resulted from the described replacement. 
If you want to augment the set of indices in an array, use 
    array_to_be_modified += array_with_indices_to_add;
Instead of calling this function, it's often faster and simpler to do this instead:

If you need references to stay intact: 
I got hit with a noob mistake. :)
When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.
With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. :) 

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)