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 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流