2

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?

3
  • what are you trying to do ? Commented Apr 26, 2015 at 15:48
  • I don't have idea how to sum same month |number| numbers which you can see in the output :) Commented Apr 26, 2015 at 15:49
  • create an array, with the month as the key, and while looping over your data add the number to that array key. Commented Apr 26, 2015 at 15:53

2 Answers 2

1

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

I know how to split and sum. But I need to sum only those numbers which are from the same month. 2015-03|1500| 2015-03|3000| 2015-03 - 4500
@mcklayin , so is the answer proper?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.