這是一個替代解決方案,它允許使用模板數組來定義輸出順序。缺失字段填寫null
或按指定填寫。在此示例中,first
和last
字段填充了---
。
請注意上一個關於數字鍵的答案中突出顯示的文字。
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" => "---"
]
您可以通過簡單的保存自己5分鐘想出來 – 2013-12-12 19:02:37