douli2063 2013-08-31 05:14
浏览 16
已采纳

结合类似的数据 - PHP中的数组

I have a 2d array such as the following:

Jan 1, 10
Jan 2, 20
Jan 2, 15
Jan 3, 20
Jan 3, 10
Jan 3, 5

And i need to create a way to scan this array, and add the numbers for similar dates into a new array, so that:

Jan 1, 10
Jan 2, 35
Jan 3, 35

What is the quickest way to accomplish this? Thank you!

  • 写回答

1条回答 默认 最新

  • douding6266 2013-08-31 05:50
    关注

    Try this

    <?php
    
    // array of monthdate structure
    $monthdate = array();
    $monthdate[] = array('date'=>'Jan 1','num'=>10);
    $monthdate[] = array('date'=>'Jan 2','num'=>20);
    $monthdate[] = array('date'=>'Jan 2','num'=>15);    
    $monthdate[] = array('date'=>'Jan 3','num'=>20);
    $monthdate[] = array('date'=>'Jan 3','num'=>10);             
    // begin the iteration for grouping date and calculate the num
    $sumofnum = array();
    foreach($monthdate as $month) {
        $index = month_exists($month['date'], $sumofnum);
        if ($index < 0) {
            $sumofnum[] = $month;
        }
        else {
            $sumofnum[$index]['num'] +=  $month['num'];
        }
    }
    print_r($sumofnum); //display 
    
    // for search if a monthdate has been added into $sumofnum, returns the key (index)
    function month_exists($monthname, $array) {
        $result = -1;
        for($i=0; $i<sizeof($array); $i++) {
            if ($array[$i]['date'] == $monthname) {
                $result = $i;
                break;
            }
        }
        return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?