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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度