doucong6884 2012-06-13 05:17
浏览 4
已采纳

对我的数组中的值求和

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)

  • 写回答

3条回答 默认 最新

  • 普通网友 2012-06-13 05:26
    关注

    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; }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度