-3

我有一个如下所示的数组,我想以特定方式计算值的总和,其中 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)

4

3 回答 3

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

?>
于 2012-06-13T05:45:56.960 回答
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; }
}
?>
于 2012-06-13T05:26:15.820 回答
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

于 2012-06-13T05:38:52.980 回答