本文實(shí)例講述了PHP實(shí)現(xiàn)數(shù)組根據(jù)某個字段進(jìn)行水平合并,橫向合并。分享給大家供大家參考,具體如下:
PHP數(shù)組水平合并,橫向合并,兩條數(shù)據(jù)合并成一行
需求
將兩個素組中日期相同的合并成一行
數(shù)組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
)
)
數(shù)組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
)
)
代碼實(shí)現(xiàn)
先將a,b數(shù)組合并,判斷當(dāng)前日期下是否空,空的話直接賦值,不空的話,將已有素組和當(dāng)前數(shù)組合并
$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);
}
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP數(shù)組(Array)操作技巧大全》、《php排序算法總結(jié)》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》、《php字符串(string)用法總結(jié)》及《PHP常用遍歷算法與技巧總結(jié)》
希望本文所述對大家PHP程序設(shè)計有所幫助。
您可能感興趣的文章:- PHP中數(shù)組合并的兩種方法及區(qū)別介紹
- php下將多個數(shù)組合并成一個數(shù)組的方法與實(shí)例代碼
- php 數(shù)組的合并、拆分、區(qū)別取值函數(shù)集
- php二維數(shù)組合并及去重復(fù)的方法
- php數(shù)組實(shí)現(xiàn)根據(jù)某個鍵值將相同鍵值合并生成新二維數(shù)組的方法
- PHP合并兩個或多個數(shù)組的方法
- php 操作數(shù)組(合并,拆分,追加,查找,刪除等)
- php通過array_merge()函數(shù)合并兩個數(shù)組的方法
- php數(shù)組合并array_merge()函數(shù)使用注意事項(xiàng)
- php合并數(shù)組并保留鍵值的實(shí)現(xiàn)方法
- php合并數(shù)組array_merge函數(shù)運(yùn)算符加號與的區(qū)別