將關聯數組與缺失列的預設值合併
要合併多個關聯數組並使用預設值填充缺失列,您可以利用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中文網其他相關文章!