【问题标题】:How to populate a pre-existing multi-dimensional array with corresponding $_POST values?如何使用相应的 $_POST 值填充预先存在的多维数组?
【发布时间】:2012-12-13 03:06:36
【问题描述】:

在不从第二个数组创建新值的情况下,我找不到一个函数可以完成 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);

注意:多维数组

【问题讨论】:

  • 你能提供两个数组的简短但真实的样本(带有样本结果)吗?

标签: php post recursion multidimensional-array overwrite


【解决方案1】:

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

我的方法包括一些重要的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',
    ),
  ),
)

【讨论】:

    【解决方案2】:

    你可能想要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)
    }
    ?>
    

    【讨论】:

    • 当然,但是是多维的?
    • 你只需要编写一个基于array_intersect_key的简单函数来检查当前键是数组还是值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2013-12-26
    • 2021-07-23
    • 2021-04-14
    • 2016-02-18
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多