【问题标题】:Sum elements from array对数组中的元素求和
【发布时间】:2015-04-26 15:47:06
【问题描述】:

这是我的脚本:

<?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>";
    }
?>

这个脚本的输出是:

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

我不知道如何计算同月的 |number|数字。梅比你能帮帮我吗?

【问题讨论】:

  • 你想做什么?
  • 我不知道如何对同月求和 |number|您可以在输出中看到的数字 :)
  • 创建一个数组,以 month 作为键,并在循环数据时将 number 添加到该数组键。

标签: php arrays numbers sum


【解决方案1】:

试试这个:

$arr = array(
'2015-04|500|',
'2015-04|1200|',
'2015-04|1000|',
'2015-04|1500|',
'2015-04|3400|',
'2015-03|1500|',
'2015-02|1500|',
'2015-03|3000|');
$st = preg_replace('/[0-9]{4}\-[0-9]{2}\||\|/','',$arr);
echo array_sum($st);

如果需要按年月求和:

$arr = array(
'2015-04|500|',
'2015-04|1200|',
'2015-04|1000|',
'2015-04|1500|',
'2015-04|3400|',
'2015-03|1500|',
'2015-02|1500|',
'2015-03|3000|');

$sub = array();
foreach($arr as $k=>$v)
{
    $value = preg_replace('/[0-9]{4}\-[0-9]{2}\||\|/','',$v);
    $key = str_replace('|'.$value.'|','',$v);
    $sub[$key][] = $value;
}

print_r($sub);
echo array_sum($sub['2015-04']);

【讨论】:

  • 我知道如何拆分和求和。但我只需要总结那些来自同一个月的数字。 2015-03|1500| 2015-03|3000| 2015-03 - 4500
  • @mcklayin ,答案正确吗?
【解决方案2】:

一个简单的方法是创建一个数组,以月份为键-

$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>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    相关资源
    最近更新 更多