本文實例講述了PHP實現數組根據某個字段進行水平合并,橫向合并。分享給大家供大家參考,具體如下:
PHP數組水平合并,橫向合并,兩條數據合并成一行
需求
將兩個素組中日期相同的合并成一行
數組a
Array
(
[0] => Array
(
[date] => 2019-04-02
[today_pay_money] => 168.00
[today_pay_num] => 1
[yesterday_pay_money] => 999.00
[yesterday_pay_num] => 1
)
[1] => Array
(
[date] => 2019-04-09
[today_pay_money] => 0.01
[today_pay_num] => 1
[yesterday_pay_money] => 0.00
[yesterday_pay_num] => 0
)
[2] => Array
(
[date] => 2019-05-05
[today_pay_money] => 0.01
[today_pay_num] => 1
[yesterday_pay_money] => 2.00
[yesterday_pay_num] => 1
)
[3] => Array
(
[date] => 2019-05-11
[today_pay_money] => 0.00
[today_pay_num] => 0
[yesterday_pay_money] =>
[yesterday_pay_num] => 1
)
)
數組B
Array
(
[0] => Array
(
[date] => 2019-05-07
[today_pay_money1] => 0
[today_pay_num1] => 0
[yesterday_pay_money1] => 0
[yesterday_pay_num1] => 0
)
[1] => Array
(
[date] => 2019-05-11
[today_pay_money1] => 0
[today_pay_num1] => 0
[yesterday_pay_money1] => 1
[yesterday_pay_num1] => 1
)
)
需要格式
Array
(
[2019-04-02] => Array
(
[date] => 2019-04-02
[today_pay_money] => 168.00
[today_pay_num] => 1
[yesterday_pay_money] => 999.00
[yesterday_pay_num] => 1
)
[2019-04-09] => Array
(
[date] => 2019-04-09
[today_pay_money] => 0.01
[today_pay_num] => 1
[yesterday_pay_money] => 0.00
[yesterday_pay_num] => 0
)
[2019-05-05] => Array
(
[date] => 2019-05-05
[today_pay_money] => 0.01
[today_pay_num] => 1
[yesterday_pay_money] => 2.00
[yesterday_pay_num] => 1
)
[2019-05-11] => Array
(
[date] => 2019-05-11
[today_pay_money] => 0.00
[today_pay_num] => 0
[yesterday_pay_money] =>
[yesterday_pay_num] => 1
[today_pay_money1] => 0
[today_pay_num1] => 0
[yesterday_pay_money1] => 1
[yesterday_pay_num1] => 1
)
[2019-05-07] => Array
(
[date] => 2019-05-07
[today_pay_money1] => 0
[today_pay_num1] => 0
[yesterday_pay_money1] => 0
[yesterday_pay_num1] => 0
)
)
代碼實現
先將a,b數組合并,判斷當前日期下是否空,空的話直接賦值,不空的話,將已有素組和當前數組合并
$total = array_merge($a,$b));
$res = array();
foreach ($total as $k => $v) {
if (empty($res[$v['date']]))
$res[$v['date']] = $v;
else
$res[$v['date']]= array_merge($res[$v['date']],$v);
}
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP數組(Array)操作技巧大全》、《php排序算法總結》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《php字符串(string)用法總結》及《PHP常用遍歷算法與技巧總結》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- PHP中數組合并的兩種方法及區別介紹
- php下將多個數組合并成一個數組的方法與實例代碼
- php 數組的合并、拆分、區別取值函數集
- php二維數組合并及去重復的方法
- php數組實現根據某個鍵值將相同鍵值合并生成新二維數組的方法
- PHP合并兩個或多個數組的方法
- php 操作數組(合并,拆分,追加,查找,刪除等)
- php通過array_merge()函數合并兩個數組的方法
- php數組合并array_merge()函數使用注意事項
- php合并數組并保留鍵值的實現方法
- php合并數組array_merge函數運算符加號與的區別