根据PHP的范围合并一些数组数据

时间:2018-06-15 19:16:52

标签: php arrays

我是这个阵列:

Array
(
    [0] => Array
        (
            [Sum] => 125.00
            [PastDays] => 530
        )

    [1] => Array
        (
            [Sum] => 123.00
            [PastDays] => 110
        )

    [2] => Array
        (
            [Sum] => 500.00
            [PastDays] => 5
        )

    [3] => Array
        (
            [Sum] => 500.00
            [PastDays] => 1
        )

)

我会根据PAY_Nb_Days

合并这些数据以使这个类型在数组上
  • 如果PAY_Nb_Days介于030之间。
  • 如果PAY_Nb_Days介于3160之间。
  • 如果PAY_Nb_Days介于6190之间。
  • 如果PAY_Nb_Days介于91120之间。
  • 如果PAY_Nb_Days高于121

所以,就像这样:

Array
(
    ['Between 0 and 30'] => Array
        (
            [Sum] => 1000.00
        )

    ['Between 31 and 60'] => Array
        (
            [Sum] => 0.00
        )

    ['Between 61 and 90'] => Array
        (
            [Sum] => 0.00
        )

    ['Between 91 and 120'] => Array
        (
            [Sum] => 123.00
        )

    ['Hight than 121'] => Array
        (
            [Sum] => 125.00
        )

)

你能告诉我从哪里开始吗?

这是我试过的:

foreach($items as $item) {
    if($item[PastDays] <= 30) { $sum_0_to_30 += $item['Sum']; } 
    if($item[PastDays] >= 31 && $item[PastDays] <= 60) { $sum_31_to_60 += $item['Sum']; }   
    if($item[PastDays] >= 61 && $item[PastDays] <= 90) { $sum_61_to_90 += $item['Sum']; }   
    if($item[PastDays] >= 91 && $item[PastDays] <= 120) { $sum_91_to_120 += $item['Sum']; } 
    if($item[PastDays] >= 121) { $sum_121 += $item['Sum']; }    
}

感谢。

1 个答案:

答案 0 :(得分:0)

$arr = [
   'Between 0 and 30'   => ['Sum' => 0],
    'Between 31 and 60'  => ['Sum' => 0],
    'Between 61 and 90'  => ['Sum' => 0],
    'Between 91 and 120' => ['Sum' => 0],
    'Hight than 121'     => ['Sum' => 0],
];





   foreach($items as $item){
         switch($item['PastDays']){
             case ($item['PastDays'] < 31):
                 $arr['Between 0 and 30']['Sum'] += $item['Sum'];
                 break;
             case ($item['PastDays'] < 61):
                 $arr['Between 31 and 60']['Sum'] += $item['Sum'];
                 break;
             case ($item['PastDays'] < 91):
                 $arr['Between 61 and 90']['Sum'] += $item['Sum'];
                 break;
             case ($item['PastDays'] < 121):
                 $arr['Between 91 and 120']['Sum'] += $item['Sum'];
                 break;
             default:
                 $arr['Hight than 121']['Sum'] += $item['Sum'];
                 break;
          }
    }

$arr将包含您需要的信息