我有一個數組,看起來像這樣:如何防止array_merge重新編號數字鍵
Array (
[0] => Array ([unit_id] => 1 [unit_name] => Clown Fish)
[1] => Array ([unit_id] => L [unit_name] => Liter)
[2] => Array ([unit_id] => 2 [unit_name] => Elephant )
[3] => Array ([unit_id] => 3 [unit_name] => Water Bottle)
[4] => Array ([unit_id] => 4 [unit_name] => Office Seating)
[5] => Array ([unit_id] => 5 [unit_name] => Green Green Grass)
)
然後,我寫了一個函數
function array_to_list($arr_data, $str_key, $str_value) {
$arr_list = array();
if (is_array($arr_data)) {
foreach($arr_data as $arr_value) {
if (isset($arr_value[$str_key]) && isset($arr_value[$str_value])) {
$arr_list = array_merge($arr_list, array($arr_value[$str_key] => $arr_value[$str_value]));
}
}
}
return $arr_list;
}
到數組轉換成這個樣子
Array (
[1] => Clown Fish)
[L] => Liter)
[2] => Elephant)
[3] => Water Bottle)
[4] => Office Seating)
[5] => Green Green Grass)
)
但是輸出,而不是
Array (
[0] => Clown Fish)
[L] => Liter)
[1] => Elephant)
[2] => Water Bottle)
[3] => Office Seating)
[4] => Green Green Grass)
)
我認爲這與array_merge本身的性質有關,它根據php手冊「輸入數組中的值與數字鍵將使用從結果數組中的零開始的遞增鍵重新編號。」
有沒有辦法讓我可以產生有或沒有array_merge的預期結果?
http://www.programmingfacts.com/merging-arrays-with-reindex-and-without-reindexing/ – PlagueEditor
感謝回答如此之快。看到解決方案非常簡單,但我在前段時間使用Google搜索時找不到它,這讓我很尷尬。謝謝。 – dqiu