dongzhao1930 2016-03-04 20:50
浏览 27
已采纳

合并日期匹配的2个数组/对象,并插入非匹配

I have 2 database objects that provide me with data over time. The results don't necessarily have the same dates however. A user could have entered just their weight one day, or body fat another day, or both on the same day.

weight_history
date - amount
Wed March 2, 2016 - 194.00
Wed March 3, 2016 - 205.40

bodyfat_history
date - amount
Wed March 1, 2016 - 24.80
Wed March 2, 2016 - 22.80

I want to graph this data so I need to merge the days that do match and then have a null in the remaining value where they don't.

The logic I'm failing to grasp is how I can add the others to get a complete data set.

Here is my code which, works for merging the data and grabbing the remaining weight results. Whats the best way to add the bodyfat results that don't match as well. If I do them inside the nested loop the data will be added multiple times.

foreach(array_reverse($weight_history->result()) as $row):
    foreach(array_reverse($bodyfat_history->result()) as $row2):
        if(date("F j, Y", $row->date) == date("F j, Y", $row2->date)){
            $results[date("F j, Y", $row->date)]['weight'] = $row->amount;
            $results[date("F j, Y", $row->date)]['bodyfat'] = $row2->amount;
        }
        $results[date("F j, Y", $row->date)]['weight'] = $row->amount;
    endforeach;
endforeach;

Here is the result set I am after.

date - weight - bodyfat
Wed March 1, 2016 - Null - 24.80
Wed March 2, 2016 - 194.00 - 22.80
Wed March 3, 2016 - 205.40 - Null

  • 写回答

1条回答 默认 最新

  • dougua2309 2016-03-04 20:56
    关注

    you don't need nested loops, try:

    foreach($weight_history->result() as $row)
        $results[date("F j, Y", $row->date)]['weight'] = $row->amount;
    foreach($bodyfat_history->result() as $row)
        $results[date("F j, Y", $row->date)]['bodyfat'] = $row->amount;
    

    in case you don't want to see warnings:

    $results = array();
    foreach($weight_history->result() as $row) {
        if (!isset($results[date("F j, Y", $row->date)])) $results[date("F j, Y", $row->date)] = array('bodyfat'=>null);
        $results[date("F j, Y", $row->date)]['weight'] = $row->amount;
    }
    foreach($bodyfat_history->result() as $row) {
        if (!isset($results[date("F j, Y", $row->date)])) $results[date("F j, Y", $row->date)] = array('weight'=>null);
        $results[date("F j, Y", $row->date)]['bodyfat'] = $row->amount;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助