将关联数组与缺失列的默认值合并
要合并多个关联数组并使用默认值填充缺失列,您可以利用 PHP 数组函数的强大功能。
问题
考虑以下数组:
$a = array('a' => 'some value', 'b' => 'some value', 'c' => 'some value'); $b = array('a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value'); $c = array('b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value');
当您使用 var_export 合并这些数组时,你得到:
array ( 0 => array ( 'a' => 'some value', 'b' => 'some value', 'c' => 'some value', ), 1 => array ( 'a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value', ), 2 => array ( 'b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value', ), )
解决方案
要组合数组键并用空字符串填充缺失的列,您可以使用 array_merge:
<code class="php">$keys = array(); foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($d)) as $key => $val) $keys[$key] = ''; $data = array(); foreach($d as $values) { $data[] = array_merge($keys, $values); }</code>
这将产生所需的输出:
Array ( [0] => Array ( [a] => some value [b] => some value [c] => some value [d] => [e] => [f] => [x] => [y] => [z] => ) [1] => Array ( [a] => another value [b] => [c] => [d] => another value [e] => another value [f] => another value [x] => [y] => [z] => ) [2] => Array ( [a] => [b] => some more value [c] => [d] => [e] => [f] => [x] => some more value [y] => some more value [z] => some more value ) )
另一个选项是创建具有空值的键对值并将它们合并:
<code class="php">$keys = array_keys(call_user_func_array('array_merge', $d)); $key_pair = array_combine($keys, array_fill(0, count($keys), null)); $values = array_map(function($e) use ($key_pair) { return array_merge($key_pair, $e); }, $d);</code>
这也会产生相同的期望输出。
以上是如何合并关联数组与缺失列的默认值?的详细内容。更多信息请关注PHP中文网其他相关文章!