是否可以使用array_split按日期拆分数据库结果?

时间:2014-04-16 03:41:40

标签: php

我不知道是否可以这样做。我从数据库返回了超过1000行,并希望在返回后使用array_split按日期拆分它们。日期采用unix时间戳的形式。

我想要做的是按日期分页这些结果。如果可以做到这一点,有人可以给我一个小例子或者指出我需要进入的方向吗?

1 个答案:

答案 0 :(得分:0)

  1. 您需要选择新字段,将格式从时间戳转换为日期字符串,然后按其排序
  2. 循环遍历结果集,当日期与先前值不同时,则创建子数组
  3. PHP代码和SQL(PS:首先必须通过'create_date'排序)

    PS:group_by函数并未真正对整个数据集进行分组!!

    $sql = " SELECT *, DATE_FORMAT(create_timestamp, '%Y-%m-%d') as create_date FROM some_table order by create_date asc";
    
    $result = mysqli_query($dblink, $sql);
    
    $grouped = group_by($result, 'create_date');
    
    
    function group_by($inArray, $keyName) {
        if (is_array($inArray) && count($inArray)>0) {
            $cabinet = array();
            $tempBox = array();
            $prevoius_value = $inArray[0][$keyName];
            for($b=0;$b<count($inArray);$b++){
                $box = $inArray[$b];
                if ($prevoius_value != $box[$keyName]){
                    array_push($cabinet, $tempBox);
                    $tempBox = array();
                    $prevoius_value = $box[$keyName];
                }
                array_push($tempBox, $box);
            }
             array_push($cabinet, $tempBox);
             return $cabinet;
        }
    }
    

    以下是样本结果:

    $result = array(
        [0] => array(
            'id' => 1,
            'name' => 'One',
            'create_timestamp' => '123456789',
            'create_date' => '2014-04-02'
        ),
    
        [1] => array(
            'id' => 1,
            'name' => 'Two',
            'create_timestamp' => '123456789',
            'create_date' => '2014-04-03'
        ),
    
        [2] => array(
            'id' => 1,
            'name' => 'Three',
            'create_timestamp' => '123456789',
            'create_date' => '2014-04-03'
        ),
    
        [3] => array(
            'id' => 1,
            'name' => 'Four',
            'create_timestamp' => '123456789',
            'create_date' => '2014-04-04'
        ),
    );
    
    $grouped = array(
        [0] => array(
            [0] => array(
                'id' => 1,
                'name' => 'One',
                'create_timestamp' => '123456789',
                'create_date' => '2014-04-02'
            )
        ),
    
        [1] => array(
            [0] => array(
                'id' => 2,
                'name' => 'Two',
                'create_timestamp' => '123456789',
                'create_date' => '2014-04-03'
            ),
    
            [1] => array(
                'id' => 3,
                'name' => 'Three',
                'create_timestamp' => '123456789',
                'create_date' => '2014-04-03'
            )
        ),
    
        [2] => array(
            [0] => array(
                'id' => 4,
                'name' => 'Four',
                'create_timestamp' => '123456789',
                'create_date' => '2014-04-04'
            )
        ),
    );