Home >Backend Development >PHP Tutorial >How to Merge Associative Arrays with Default Values for Missing Columns?
Merging Associative Arrays with Default Values for Missing Columns
To merge multiple associative arrays and fill in missing columns with a default value, you can leverage the power of PHP's array functions.
The Problem
Consider the following arrays:
$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');
When you merge these arrays using var_export, you get:
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', ), )
The Solution
To combine the array keys and fill in missing columns with an empty string, you can use 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>
This will produce the desired output:
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 ) )
Another option is to create key-pair values with empty values and merge them:
<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>
This will also produce the same desired output.
The above is the detailed content of How to Merge Associative Arrays with Default Values for Missing Columns?. For more information, please follow other related articles on the PHP Chinese website!