テンプレート配列を使用して出力順序を定義できる代替ソリューションを次に示します。欠落しているフィールドは、null
または指定どおりに入力されます。この例では、first
andlast
フィールドは。で埋められてい---
ます。
数字キーに関する前の回答から強調表示されたテキストに注意してください。
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);
}
入力:
$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'];
出力:
/* 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" => "---"
]