PHP实现数组根据某个字段进行水平合并,横向合并案例分析

本文实例讲述了PHP实现数组根据某个字段进行水平合并,横向合并。分享给大家供大家参考,具体如下:

PHP数组水平合并,横向合并,两条数据合并成一行

需求

将两个素组中日期相同的合并成一行

数组a

  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [date] => 2019-04-02
  6. [today_pay_money] => 168.00
  7. [today_pay_num] => 1
  8. [yesterday_pay_money] => 999.00
  9. [yesterday_pay_num] => 1
  10. )
  11. [1] => Array
  12. (
  13. [date] => 2019-04-09
  14. [today_pay_money] => 0.01
  15. [today_pay_num] => 1
  16. [yesterday_pay_money] => 0.00
  17. [yesterday_pay_num] => 0
  18. )
  19. [2] => Array
  20. (
  21. [date] => 2019-05-05
  22. [today_pay_money] => 0.01
  23. [today_pay_num] => 1
  24. [yesterday_pay_money] => 2.00
  25. [yesterday_pay_num] => 1
  26. )
  27. [3] => Array
  28. (
  29. [date] => 2019-05-11
  30. [today_pay_money] => 0.00
  31. [today_pay_num] => 0
  32. [yesterday_pay_money] =>
  33. [yesterday_pay_num] => 1
  34. )
  35. )

数组B

  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [date] => 2019-05-07
  6. [today_pay_money1] => 0
  7. [today_pay_num1] => 0
  8. [yesterday_pay_money1] => 0
  9. [yesterday_pay_num1] => 0
  10. )
  11. [1] => Array
  12. (
  13. [date] => 2019-05-11
  14. [today_pay_money1] => 0
  15. [today_pay_num1] => 0
  16. [yesterday_pay_money1] => 1
  17. [yesterday_pay_num1] => 1
  18. )
  19. )

需要格式

  1. Array
  2. (
  3. [2019-04-02] => Array
  4. (
  5. [date] => 2019-04-02
  6. [today_pay_money] => 168.00
  7. [today_pay_num] => 1
  8. [yesterday_pay_money] => 999.00
  9. [yesterday_pay_num] => 1
  10. )
  11. [2019-04-09] => Array
  12. (
  13. [date] => 2019-04-09
  14. [today_pay_money] => 0.01
  15. [today_pay_num] => 1
  16. [yesterday_pay_money] => 0.00
  17. [yesterday_pay_num] => 0
  18. )
  19. [2019-05-05] => Array
  20. (
  21. [date] => 2019-05-05
  22. [today_pay_money] => 0.01
  23. [today_pay_num] => 1
  24. [yesterday_pay_money] => 2.00
  25. [yesterday_pay_num] => 1
  26. )
  27. [2019-05-11] => Array
  28. (
  29. [date] => 2019-05-11
  30. [today_pay_money] => 0.00
  31. [today_pay_num] => 0
  32. [yesterday_pay_money] =>
  33. [yesterday_pay_num] => 1
  34. [today_pay_money1] => 0
  35. [today_pay_num1] => 0
  36. [yesterday_pay_money1] => 1
  37. [yesterday_pay_num1] => 1
  38. )
  39. [2019-05-07] => Array
  40. (
  41. [date] => 2019-05-07
  42. [today_pay_money1] => 0
  43. [today_pay_num1] => 0
  44. [yesterday_pay_money1] => 0
  45. [yesterday_pay_num1] => 0
  46. )
  47. )

代码实现

先将a,b数组合并,判断当前日期下是否空,空的话直接赋值,不空的话,将已有素组和当前数组合并

  1. $total = array_merge($a,$b));
  2. $res = array();
  3. foreach ($total as $k => $v) {
  4. if (emptyempty($res[$v['date']]))
  5. $res[$v['date']] = $v;
  6. else
  7. $res[$v['date']]= array_merge($res[$v['date']],$v);
  8. }