Here is an alternative solution that allows the use of a template array to define the output order. Missing fields are filled with null
or as specified. In this example the first
and last
fields are filled with ---
.
Please take note of the highlighted text from the previous answer about numeric keys.
function array_merge_template($array1, $array2, $template, $fill=null) {
$_template = array_fill_keys($template, $fill);
return array_intersect_key ( array_replace ( $_template, array_merge($array1, $array2)) , $_template);
}
Input:
$array1 = ['username' =>'abc', 'level' =>'admin', 'status' =>'active', 'foo'=>'x'];
$array2 = ['level' =>'root', 'status' =>'active', 'username' =>'bcd', 'bar'=>'y'];
$template = ['first','level','foo','username','bar','status','last'];
Output:
/* array_merge($array1,$array2) */
[
"username" => "bcd",
"level" => "root",
"status" => "active",
"foo" => "x",
"bar" => "y"
]
/* array_merge_template($array1,$array2,$template,'---') */
[
"first" => "---",
"level" => "root",
"foo" => "x",
"username" => "bcd",
"bar" => "y",
"status" => "active",
"last" => "---"
]