按字段范围的数组数据

时间:2013-12-12 12:33:27

标签: php sql arrays sorting date-sorting

我有一个包含字段日期和价格的数据库(图片如下)

enter image description here

我想做一个像:

的结果

天|价

1-3 | 5

4 | 6

7-8 | 10

13+ | 20

我认为制作(将这些工作交给sql)对数据库来说很难(我说的是速度)

数据库结果:

Array
(
    [0] => Array
        (
            [id] => 1
            [day] => 1
            [price] => 5
        )

    [1] => Array
        (
            [id] => 2
            [day] => 2
            [price] => 5
        )

    [2] => Array
        (
            [id] => 3
            [day] => 3
            [price] => 5
        )

    [3] => Array
        (
            [id] => 4
            [day] => 4
            [price] => 6
        )

    [4] => Array
        (
            [id] => 7
            [day] => 7
            [price] => 10
        )

    [5] => Array
        (
            [id] => 8
            [day] => 8
            [price] => 10
        )

    [6] => Array
        (
            [id] => 9
            [day] => 13
            [price] => 20
        )

)

现在我正在考虑循环数组,但不知道如何解决这些问题

1 个答案:

答案 0 :(得分:2)

您的问题可以通过单循环解决:

$array = [
   ['id'=>2, 'day'=>2, 'price'=>5],
   ['id'=>5, 'day'=>3, 'price'=>7],
   ['id'=>7, 'day'=>8, 'price'=>8],
   ['id'=>6, 'day'=>4, 'price'=>5],
   ['id'=>1, 'day'=>1, 'price'=>5],
   ['id'=>9, 'day'=>9, 'price'=>8],
   ['id'=>11, 'day'=>13, 'price'=>10],
   ['id'=>15, 'day'=>12, 'price'=>10]
];
//sort by day. You can skip this if perform ORDER BY `day` in DBMS
usort($array, function($x, $y)
{
   return $x['day']-$y['day'];
});

$price  = current($array)['price'];
$min    = current($array)['day'];
$max    = $min;
$result = [];

foreach($array as $i=>$item)
{
   if($price!=$item['price'])
   {
      $result[] = ['day' => $min==$max?$min:$min.'-'.$max, 'price'=>$price];
      $min = $item['day'];
      $max = $min;
   }
   else
   {
      $max = $item['day']; 
   }
   $price = $item['price'];   
}
$result[] = ['day' => $min.'+', 'price'=> $price];

最终结果将如下所示:

Array
(
    [0] => Array
        (
            [day] => 1-2
            [price] => 5
        )

    [1] => Array
        (
            [day] => 3
            [price] => 7
        )

    [2] => Array
        (
            [day] => 4
            [price] => 5
        )

    [3] => Array
        (
            [day] => 8-9
            [price] => 8
        )

    [4] => Array
        (
            [day] => 12+
            [price] => 10
        )

)