合并关联数组并用默认值补全缺失的列
考虑以下代码:
<code class="php">$a = ['a' => 'some value', 'b' => 'some value', 'c' => 'some value']; $b = ['a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value']; $c = ['b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value']; $d = [$a, $b, $c];</code>
当您使用 var_export($d),您将得到以下输出:
<code class="php">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', ), )</code>
将数组键与默认值合并
组合数组键并填充缺失的列使用默认值,您可以使用 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); } echo '<pre class="brush:php;toolbar:false">'; print_r($data);</code>
结果:
<code class="php">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>
另一种方法
或者,您可以创建密钥对值,然后合并它们:
<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 中有效地合并关联数组并处理缺失列?的详细内容。更多信息请关注PHP中文网其他相关文章!