douxia1988 2015-04-26 15:47
浏览 102
已采纳

从数组求和元素

Here is my script:

<?php   
    $failas = fopen("info.txt", "r");
    while (!feof($failas)){
        $d = fgets($failas);
        $dExploded = explode ( "|", $d );
        list($dDate, $dTime) = explode(" ", $dExploded[substr_count($d, "|")]);
        $metmen[] = implode('-', explode('-', $dDate, -1));
        if(preg_match_all('/[|]\d+[|]/', $d, $match)){
            $numbers[] = implode('', $match[0]);
        } 
    }
    fclose($failas);
    foreach ($numbers as $key=>$value)
    {
        $naujas[$key] = $metmen[$key] . $numbers[$key];
        print $naujas[$key] . "<br>";
    }
?>

The output of this script is:

2015-04|500|
2015-04|1200|
2015-04|1000|
2015-04|1500|
2015-04|3400|
2015-03|1500|
2015-02|1500|
2015-03|3000|

I don't have idea how to sum same month |number| numbers. Maby you can help me?

  • 写回答

2条回答 默认 最新

  • doushihu5475 2015-04-26 16:10
    关注

    An easy way to do this is to create an array, with the month being the key-

    $months = array();
    foreach ($numbers as $key=>$value)
    {
        $month = rtrim("|",$metmen[$key]);
        $number = rtrim("|",$numbers[$key]);
        $months[$month] = isset($months[$month]) ? $months[$month]+$number : $number;
    }
    //print each month/sum
    foreach($months as $month=>$number){
        print $month.' - '.$number . "<br>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作