对数组进行分组并在特定范围内相加值

时间:2018-11-25 13:49:36

标签: php arrays

我有这个数组:

Array
(
    [0] => Array(
        [number] => 50
        [amount] => 0.04
        )

    [1] => Array(
        [number] => 50
        [amount] => 0.04
        )

    [2] => Array(
        [number] => 50
        [amount] => 0.04
        )

    [3] => Array(
        [number] => 100
        [amount] => 0.04
        )

    [4] => Array(
        [number] => 150
        [amount] => 0.04
        )
)

我希望将所有人数总计在0到50、51到100和101到150的范围内。

必填结果:
0至50 = 0.2(总计0.04,因为数字100和150也有50)
51至100 = 0.08
101至150 = 0.04

有人可以给我解决办法吗?

3 个答案:

答案 0 :(得分:1)

当您要将其添加到一组结果字段时,我使用了嵌套的foreach()方法。最主要的是,我已经定义了一个$results数组,该数组定义了该结果的起点。

它将遍历源数组中的每个项目,然后遍历每个结果字段,如果源项目大于结果的开始,则它将停止查找并移至下一个源项目...

$results = [ [ "from" => 0, "total" => 0],
    [ "from" => 100, "total" => 0],
    [ "from" => 150, "total" => 0]
];
foreach ( $data as $item )  {
    foreach ( $results as $key => $result ) {
        if ( $result["from"] > $item["number"] )    {
            break;
        }
        $results [ $key ]["total"] += $item["amount"];
    }
}

print_r(array_column($results,"total"));

打印出

Array
(
    [0] => 0.2
    [1] => 0.08
    [2] => 0.04
)

答案 1 :(得分:0)

您可以尝试使用array_reducearray_filter的组合

function toFifty($value)
{
  return $value['number'] >= 0 && $value['number'] < 51;
}

function toHundred($value)
{
  return $value['number'] >= 51 && $value['number'] < 101;
}

function toHundredFifty($value)
{
  return $value['number'] >= 101 && $value['number'] < 151;
}

function sum($carry, $item)
{
    return $carry + $item['amount'];
}

var_dump(array_reduce(array_filter($array, 'toFifty'), 'sum'));
var_dump(array_reduce(array_filter($array, 'toHundred'), 'sum'));
var_dump(array_reduce(array_filter($array, 'toHundredFifty'), 'sum'));  

答案 2 :(得分:0)

您还可以做的是在数组中指定范围。然后使用array_filter循环数组并获得小于或等于当前数字的范围。对于每个范围,然后使用范围中的值作为键添加金额:

$ranges = [50,100,150];
$result = [];
$items = [
    [
        "number" => 50,
        "amount" => 0.04
    ],
    [
        "number" => 50,
        "amount" => 0.04
    ],
    [
        "number" => 50,
        "amount" => 0.04
    ],
    [
        "number" => 100,
        "amount" => 0.04
    ],
    [
        "number" => 150,
        "amount" => 0.04
    ]
];

foreach ($items as $item) {
    $validRanges  = array_filter($ranges, function($range) use ($item){
        return $range <= $item["number"];
    });
    foreach ($validRanges as $validRange) {
        if (!array_key_exists($validRange, $result)) {
            $result[$validRange] = $item["amount"];
            continue;
        }
        $result[$validRange] += $item["amount"];
    }
}

print_r($result);

结果

Array
(
    [50] => 0.2
    [100] => 0.08
    [150] => 0.04
)

Demo