【问题标题】:Sum array values depending dates non-singularity根据日期非奇点对数组值求和
【发布时间】:2013-06-02 20:55:03
【问题描述】:

假设我有 2 个大小相同的数组,其中填充了值。 dates 数组包含字符串格式的日期,costs 数组包含数字成本。 例如:

$dates = array('2001-01-01', '2001-02-01', '2001-02-01', '2001-02-01', '2001-03-01', '2001-04-01', '2001-04-01', '2001-05-01');
$costs = array(5, 10, 20, 4, 30, 14, 2, 0);

我想要的是仅当 $dates 数组中的日期重复时,才将成本数组中的数字相加到一个新数组中。发生这种情况时,新数组值必须是其“左兄弟”的总和。其余新数组值应为 0。在其他情况下(当日期在数组中唯一时,则新数组值是0).

这应该是上述过程的结果:

$newarr = array(5, 0, 0, 34, 30, 0, 16, 0);

【问题讨论】:

    标签: php arrays sum


    【解决方案1】:

    这个怎么样?

    $result = $costs;
    foreach ($dates as $i => $d) {
        if ($i > 0 && $dates[$i - 1] == $dates[$i]) {
            $result[$i] += $result[$i - 1];
            $result[$i - 1] = 0;
        }
    }
    print_r($result);
    

    我们从 $costs 数组开始,遍历所有日期...每次我们检测到日期与前一个条目相同时,我们将前一个条目清零并将其值添加到我们的当前位置。

    替代解决方案

    这不是您所要求的,但我怀疑更有用的解决方案可能是这样的:

    $result = array();
    foreach ($dates as $i => $d) {
        $result[$d] = (isset($result[$d]) ? $result[$d] : 0) + $costs[$i];
    }
    print_r($result);
    

    这将产生以下结果:

    array(
        '2001-01-01' => 5,
        '2001-02-01' => 34,
        '2001-03-01' => 30,
        '2001-04-01' => 16,
        '2001-05-01' => 0
    )
    

    【讨论】:

    • 伙计……这太快了!您在发布替代解决方案后也成功了,这比我想象的还要好!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2018-08-01
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多