phpsqlarrayssortingdate-sorting

Range array data by field


I have a database with fields day and prices(image below)

enter image description here

I want to make a result something like :

day | price

1-3 | 5

4 | 6

7-8 | 10

13+ | 20

I think making (giving these job to sql) it will be hard for database (I'm speaking about speed)

Database result:

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
        )

)

Now I am thinking about loop an array but do not have an idea how to solve these problem


Solution

  • Your issue can be resolved with single loop:

    $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];
    

    end result will look like this:

    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
            )
    
    )