对我的数组中的值求和

I have an array like below, and I want to do the total of values in a specific manner where all values of ADDED_NEW_(.*) {regular expressions}, and similarly other values. I have only specific vals like ADDED_NEW, ADDED_OLD, and ADD_LATER.

My array is like:

$stats = Array
(
    [ADDED_NEW_2012_06_12] => 16
    [ADDED_OLD_2012_06_12] => 10
    [ADD_LATER_2012_06_12] => 12
    [ADDED_NEW_2012_06_11] => 16
    [ADDED_OLD_2012_06_11] => 10
    [ADD_LATER_2012_06_11] => 12
)

Can you please tell me how can i obtain my result. I don't know how to add such values using regex in php. Please help.

The output I am expecting is $ADDED_NEW = 32 (i.e. 16+16), $ADDED_OLD = 20 (i.e. 10+10) and $ADD_LATER = 24 (i.e. 12+12)

I believe you just want to add values of similar keys in which they all start with ADDED_NEW or ADDED_OLD or ADD_LATER I assume so we can just make 3 counters and just match for those in the key and add to the counters.

I don't know much PHP but using manuals and my knowledge from Python, this is what I mustered up:

<?php
$ADDED_NEW = 0;
$ADDED_OLD = 0;
$ADD_LATER = 0;
foreach ($stats as $key => $value) {
    if (preg_match("ADDED_NEW_.*", $key)) { $ADDED_NEW += $value; }
    if (preg_match("ADDED_OLD_.*", $key)) { $ADDED_OLD += $value; }
    if (preg_match("ADD_LATER_.*", $key)) { $ADD_LATER += $value; }
}
?>

check this out.

<?php



   $stats = array(
    'ADDED_NEW_2012_06_12' => 16,
    'ADDED_OLD_2012_06_12' => 10,
    'ADD_LATER_2012_06_12' => 12,
    'ADDED_NEW_2012_06_11' => 16,
    'ADDED_OLD_2012_06_11' => 10,
    'ADD_LATER_2012_06_11' => 12
);
    $ADDED_NEW = 0;
    $ADDED_OLD = 0;
    $ADD_LATER = 0;
    foreach ($stats as $key => $value) {
        if (preg_match("/ADDED_NEW_.*/", $key)) { $ADDED_NEW += $value; }
        else if (preg_match("/ADDED_OLD_.*/", $key)) { $ADDED_OLD += $value; }
        else if (preg_match("/ADD_LATER_.*/", $key)) { $ADD_LATER += $value; }
    }

echo "$ADDED_NEW - $ADDED_OLD - $ADD_LATER";

?>

outputs: 32 - 20 - 24

Try this:

<?php

$stats = array
(
    "ADDED_NEW_2012_06_12" => 16,
    "ADDED_OLD_2012_06_12" => 10,
    "ADD_LATER_2012_06_12" => 12,
    "ADDED_NEW_2012_06_11" => 16,
    "ADDED_OLD_2012_06_11" => 10,
    "ADD_LATER_2012_06_11" => 12,
);

$accumulators = array
(
    "ADDED_NEW" => 0,
    "ADDED_OLD" => 0,
    "ADD_LATER" => 0,
);

foreach($stats as $key => $value)
{
    foreach(array_keys($accumulators) as $accumulator)
    {
        if(preg_match("@^${accumulator}@m", $key)){$accumulators[$accumulator] += $value;}
    }
}

header('Content-Type: text/plain');
print_r($accumulators);

?>