PHP实现数组根据某个字段进行水平合并,横向合并案例分析
这篇文章主要介绍了PHP实现数组根据某个字段进行水平合并,横向合并,结合具体案例形式分析了php数组遍历、合并等相关操作技巧,需要的朋友可以参考下本文实例讲述了PHP实现数组根据某个字段进行水平合并,横向合并。分享给大家供大家参考,具体如下:
PHP数组水平合并,横向合并,两条数据合并成一行
需求
将两个素组中日期相同的合并成一行
数组a
Array
(
=> Array
(
=> 2019-04-02
=> 168.00
=> 1
=> 999.00
=> 1
)
=> Array
(
=> 2019-04-09
=> 0.01
=> 1
=> 0.00
=> 0
)
=> Array
(
=> 2019-05-05
=> 0.01
=> 1
=> 2.00
=> 1
)
=> Array
(
=> 2019-05-11
=> 0.00
=> 0
=>
=> 1
)
)
数组B
Array
(
=> Array
(
=> 2019-05-07
=> 0
=> 0
=> 0
=> 0
)
=> Array
(
=> 2019-05-11
=> 0
=> 0
=> 1
=> 1
)
)
需要格式
Array
(
=> Array
(
=> 2019-04-02
=> 168.00
=> 1
=> 999.00
=> 1
)
=> Array
(
=> 2019-04-09
=> 0.01
=> 1
=> 0.00
=> 0
)
=> Array
(
=> 2019-05-05
=> 0.01
=> 1
=> 2.00
=> 1
)
=> Array
(
=> 2019-05-11
=> 0.00
=> 0
=>
=> 1
=> 0
=> 0
=> 1
=> 1
)
=> Array
(
=> 2019-05-07
=> 0
=> 0
=> 0
=> 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程序设计有所帮助。
原文链接:https://blog.csdn.net/flysnownet/article/details/90111860
http://www.zzvips.com/article/186759.html
页:
[1]