Albance
Albance

Reputation: 167

Sum elements from array

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?

Upvotes: 2

Views: 53

Answers (2)

mcklayin
mcklayin

Reputation: 1360

Try this:

$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);

If you need to summ by year-month:

$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']);

Upvotes: 1

Sean
Sean

Reputation: 12433

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

Upvotes: 0

Related Questions