从数组求和元素

时间:2015-04-26 15:47:07

标签: php arrays numbers sum

这是我的剧本:

<?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|

我不知道如何总结同月|数字|数字。 Maby你可以帮帮我吗?

2 个答案:

答案 0 :(得分: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']);

答案 1 :(得分:0)

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

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