首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按字段划分的范围数组数据

按字段划分的范围数组数据
EN

Stack Overflow用户
提问于 2013-12-12 12:33:26
回答 1查看 59关注 0票数 1

我有一个有字段、日期和价格的数据库(下图)

我想得出这样的结果:

日价格

1-3 -5

4/6

7-8 - 10

13+ \x{e76f} 20

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

数据库结果:

代码语言:javascript
复制
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
        )

)

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-12 13:54:04

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

代码语言:javascript
复制
$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];

最终结果如下所示:

代码语言:javascript
复制
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
        )

)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20543694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档