合并两个数组使用相同的密钥,但在不同的深度? [英] Merge two arrays with the same key but in different depth?

查看:188
本文介绍了合并两个数组使用相同的密钥,但在不同的深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ ARR =数组('一'=>阵列('one_1'=>阵列('one_2'=>'12')),两,三');
$ ARR2 =阵列('one_2'=>'十二');$合并= array_merge($改编,$ ARR2);打印'< pre>';
后续代码var_dump($合并);
打印'< / pre>';

给出了:

 阵列(4){
  [一] =>
  阵列(1){
    [one_1] =>
    阵列(1){
      [one_2] =>
      串(2)12
    }
  }
  [0] =>
  串(3)两节
  [1] =>
  串(5)三
  [one_2] =>
  字符串(6)十二条
}

我要在第一阵列中键 one_2 的值与第二阵列中的同一个键的值代替。这样的结果将是:

 阵列(4){
  【一] =>
  阵列(1){
    [one_1] =>
    阵列(1){
      [one_2] =>
      字符串(2)十二条
    }
  }
  [0] =>
  串(3)两节
  [1] =>
  串(5)三
}


解决方案

  array_walk_recursive($ ARR,功能(安培; $价值$键,$替代){
    如果(使用isset($替换[$关键])){
        $值= $替换[$关键];
    }
},$ ARR2);

请注意,这里使用PHP 5.3+的语法。

$arr = array('one' => array('one_1' => array('one_2' => '12')), 'two', 'three');
$arr2 = array('one_2' => 'twelve');

$merge = array_merge($arr, $arr2);

print '<pre>';
var_dump($merge);
print '</pre>';

gives:

  array(4) {
  ["one"]=>
  array(1) {
    ["one_1"]=>
    array(1) {
      ["one_2"]=>
      string(2) "12"
    }
  }
  [0]=>
  string(3) "two"
  [1]=>
  string(5) "three"
  ["one_2"]=>
  string(6) "twelve"
}

I want the value of key one_2 in the first array to be replaced with the value of the same key in the second array. So the result would be:

array(4) {
  ["one"]=>
  array(1) {
    ["one_1"]=>
    array(1) {
      ["one_2"]=>
      string(2) "twelve"
    }
  }
  [0]=>
  string(3) "two"
  [1]=>
  string(5) "three"
}

解决方案

array_walk_recursive($arr, function (&$value, $key, $replacements) {
    if (isset($replacements[$key])) {
        $value = $replacements[$key];
    }
}, $arr2);

Note that this uses PHP 5.3+ syntax.

这篇关于合并两个数组使用相同的密钥,但在不同的深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆