Php - 对数组中的每2个元素求和

时间:2018-02-20 06:06:17

标签: php sum

我有一个这种类型的数组:

array(4) {
    [0] =>
    array(4) {
            ["type"] =>
            string(2)
            "up" ["size"] =>
            float(7.4856046065259)
        }
        [1] =>
        array(4) {
            ["type"] =>
            string(4)
            "down" ["size"] =>
            float(-2.6785714285714)
        }
        [2] =>
        array(4) {
            ["type"] =>
            string(2)
            "up" ["size"] =>
            float(3.103119266055)
        }
        [3] =>
        array(4) {
            ["type"] =>
            string(4)
            "down" ["size"] =>
            float(-2.5251284898703)
        }
}

基本上我需要区分每个up&向下(每2个值加起来)。在php中有没有有效的方法呢?

我尝试了一个复杂的功能,但不是很方便:

foreach($array as $fa)
        {
            if($fa_count >= 2)
            {
                $fa_count = 0;
                $fa_change = 0;

                $fa_change = $fa_change + $fa["size"];
                $fa_count++;
            }
            else
            {
                $fa_change = $fa_change + $fa["size"];
                $fa_count++;
            }

        }

1 个答案:

答案 0 :(得分:0)

显然你正在做这样的事情:

$count  = 0;
$fa_change = 0;
array_map (
    function($fa) use (&$count, &$fa_change) {
        $count++;
        $fa_change+= ('up' === $fa['type'] ? 1 : -1) * $fa['size'];
    },
    $array
);

假设array 的所有元素都定义了'type'和'size',否则添加一个支票:

        if   (is_array($fa)
           && isset($fa['size']) 
           && isset($fa['type']) 
           && in_array($fa['type'], [ 'up', 'down' ])
        ) {
            $fa_change+= ('up' === $fa['type'] ? 1 : -1) * $fa['size'];
        }

或者更好的断言:

        assert ('is_array($fa) && isset($fa["size"]) && isset($fa["type"]) && in_array($fa["type"], array( "up", "down" ))", 'array is not correctly formed');
        $fa_change+= ('up' === $fa['type'] ? 1 : -1) * $fa['size'];

但你想要的略有不同:

  

我需要区分每个

$result = [ ];
foreach ($array as $index => $fa) {
    // Check that $fa is an array and it has $fa['size']
    if ($index % 2) {
        // Check that $fa['type'] here is really DOWN
        $result[] = [ 'change' => $change - $fa['size'] ];
        unset($change);
    } else {
        // Check that $fa['type'] here is really UP
        $change = $fa['size'];
    }
}
if (isset($change)) {
    // There was one item left, and it was 'up'.
    $result = [ 'change' => $change ];
}

最后,$result将有$array项目的一半。