dongye9182 2016-05-09 18:17
浏览 69
已采纳

使用相同的键组合索引数组

I am using the Flot jQuery plugin to create a graph on how many visitors there have been per platform. I would like to create a 4th line with total visitors, calculated by previously retrieved data.

I need to combine several multi-dimensional Indexed arrays, but not simply merging them recursively. I.E:

$arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
$arr2 = [[2016/05/04,1],[2016/05/03,3],[2016/05/02,2]];
$arr3 = [[2016/05/04,6],[2016/05/03,7],[2016/05/02,8]];

The output should be:

$arrTotal = [[2016/05/04,9],[2016/05/03,14],[2016/05/02,16]];

How do I accomplish this in a (fairly) simple way?

  • 写回答

3条回答 默认 最新

  • doujupa7567 2016-05-09 18:34
    关注

    First of all, you cannot declare your dates the way you did:

    $arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
    

    Because it's going to take 2016, divide it by 5 then divide it by 4. You need to put them into quotes.

    $arr1 = [['2016/05/04',2],['2016/05/03',4],['2016/05/02',6]];
    

    But to create an associative array, you should do it this way:

    $arr1 = array('2016/05/04' => 2, '2016/05/03' => 4, '2016/05/02' => 6);
    $arr2 = array('2016/05/04' => 1, '2016/05/03' => 3, '2016/05/02' => 2);
    $arr3 = array('2016/05/04' => 6, '2016/05/03' => 7, '2016/05/02' => 8);
    

    Now all you want to do, is loop through each array and sum them up.

    $merge = array();
    
    function mergeArray(Array &$merge, Array $array){
        // Loop through each key and value
        foreach($array as $key => $value)
            // Make sure the value is numeric
            if(is_numeric($value)){
                if(!isset($merge[$key]))
                    $merge[$key] = $value;
                else
                    $merge[$key] += $value;
            }
    }
    
    mergeArray($merge, $arr1);
    mergeArray($merge, $arr2);
    mergeArray($merge, $arr3);
    

    And now if you dump the $merge:

    array(3) {
        ["2016/05/04"]=>
            int(9)
        ["2016/05/03"]=>
            int(14)
        ["2016/05/02"]=>
            int(16)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程