0

array_replace_recursive如果不从第二个数组创建新值,我找不到一个函数。

基本上,出于建设性目的,我有这个带有空值的数组。然后我想从中复制$_POST具有相同键的数据。但我不希望复制外键的值。

$array = array(
  'one' => '',
  'two' => array(
    'this' => '',
    'that' => '',
  ),
  // ...
);

$_POST = array(
  'one' => 'a',
  'two' => array(
    'this' => 'b',
    'that' => 'c',
    'dontcopyme' => '...',
  ),
  'dontcopyme' => 'x',
  // ...
);

//$new_array = array_merge_recursive($array, $_POST);
//$new_array = array_replace_reursive($array, $_POST);
$new_array = array_dosomemagic($array, $_POST);

在这个示范案例中我所追求的结果:

array(
  'one' => 'a'
  'two' => array(
    'this' => 'b'
    'that' => 'c'
  )
)

print_r($new_array);

注意:多维数组

4

2 回答 2

0

对不起,这不是一个性感的单行,但递归很难塞进一行。

我的方法包括一些重要isset()的检查,以确保数组元素在尝试访问它们之前存在。您不应该在我的函数中看到任何警告/通知。

代码:(演示

function recursivePopulate($defaults,$post){
    foreach($defaults as $key=>&$elem){  // make $elem modifiable by reference
        if(!is_array($elem) && isset($post[$key])){  // if not an array and matching element in $_POST
            $elem=$post[$key];  // store $post 
        }elseif(isset($post[$key])){  // only recurse subarray if exists in BOTH arrays
            $elem=recursivePopulate($elem,$post[$key]); // recurse using subarray
        }
    }
    return $defaults;
}

$defaults=[
    'one'=>'one',
    'two'=>[
        'this'=>'this',
        'that'=>'that',
            ['deep'=>'no match']
    ]
];

$_POST=[
  'one'=>'New One',
  'two'=>[
    'this'=>'New This',
    'that'=>'New That',
    'dontcopyme'=>'...'
  ],
  'dontcopyme' => 'X'
];

var_export(recursivePopulate($defaults,$_POST));

输出:

array (
  'one' => 'New One',
  'two' => 
  array (
    'this' => 'New This',
    'that' => 'New That',
    0 => 
    array (
      'deep' => 'no match',
    ),
  ),
)
于 2017-09-08T09:40:34.183 回答
-1

你可能想要array_intersect_key()

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}
?>
于 2012-12-27T18:40:38.097 回答