如何使用相应的$ _POST值填充预先存在的多维数组?

时间:2012-12-27 18:38:09

标签: php post recursion multidimensional-array overwrite

我找不到一个函数来执行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);

注意:多维数组

2 个答案:

答案 0 :(得分:0)

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

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

代码:(Demo

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',
    ),
  ),
)

答案 1 :(得分:-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)
}
?>