我有兩個數組,即arr和arr2。具有公共值的合併陣列
var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}];
var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];
是否有可能從上面的數組中獲得數組?
result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];
如果我使用array_merge然後我得到的答案
result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];
發生這種情況是因爲如果鍵是數字,'array_merge'不會合並,而是追加新的數據。從PHP手冊:*如果輸入數組具有相同的字符串鍵,則該鍵的後面的值將覆蓋前一個。但是,如果數組中包含數字鍵,則後面的值不會覆蓋原始值,但會被追加。* – tilz0R
ok先生。有沒有可能獲得預期的答案? – Raj
在使用array_merge或更好的array_merge_recursive合併在一起之前,請確保您的數組包含非數字鍵。例如,您可以將月份名稱設置爲月份數據的關鍵字。 – tilz0R