对我的数组中的值求和

时间:2012-06-13 05:17:42

标签: php regex arrays

我有一个如下所示的数组,我希望以特定方式完成值的总和,其中ADDED_NEW _(。*){正则表达式}的所有值,以及类似的其他值。 我只有像ADDED_NEW,ADDED_OLD和ADD_LATER这样的特定值。

我的数组就像:

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

你能告诉我怎样才能获得我的结果。我不知道如何在php中使用正则表达式添加这些值。请帮忙。

我期待的输出是$ ADDED_NEW = 32(即16 + 16),$ ADDED_OLD = 20(即10 + 10)和$ ADD_LATER = 24(即12 + 12)

3 个答案:

答案 0 :(得分:0)

我相信您只想添加类似键的值,其中所有键都以ADDED_NEW或ADDED_OLD或ADD_LATER开头我假设我们可以只生成3个计数器,只匹配键中的那些并添加到计数器。

我不太了解PHP,但是使用手册和Python的知识,这就是我的工作:

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

答案 1 :(得分:0)

检查一下。

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

?>

输出: 32 - 20 - 24

答案 2 :(得分:0)

试试这个:

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

?>