数组格式和排序

时间:2016-06-29 00:38:43

标签: php arrays

今天凌晨3点,我累得太累了,我不知道如何让这件事情发挥作用。 从数据库返回以下数组,其中包含过去7天的页面视图,日期和消息等信息:

Array
(
  [0] => Array
    (
        [vws] => 9
        [mss] => 0
        [dt] => 2016-06-27
    )

  [1] => Array
    (
        [vws] => 4
        [mss] => 0
        [dt] => 2016-06-26
    )

  [2] => Array
    (
        [vws] => 1
        [mss] => 0
        [dt] => 2016-06-24
    )

  [3] => Array
    (
        [vws] => 7
        [mss] => 0
        [dt] => 2016-06-23
    )

)

即使没有网页浏览量或消息,此数组也应包含数据,因此我正在寻找:

Array
(
  [0] => Array
    (
        [vws] => 0
        [mss] => 0
        [dt] => 2016-06-22
    )

  [1] => Array
    (
        [vws] => 13
        [mss] => 1
        [dt] => 2016-06-23
    )

  [2] => Array
    (
        [vws] => 7
        [mss] => 3
        [dt] => 2016-06-24
    )

  [3] => Array
    (
        [vws] => 45
        [mss] => 10
        [dt] => 2016-06-25
    )

  [4] => Array
    (
        [vws] => 0
        [mss] => 0
        [dt] => 2016-06-26
    )

  [5] => Array
    (
        [vws] => 0
        [mss] => 0
        [dt] => 2016-06-27
    )

  [6] => Array
    (
        [vws] => 5
        [mss] => 1
        [dt] => 2016-06-28
    )

)

很抱歉,如果我不够清楚的话。如果您需要更多信息,我会更新我的问题。 提前谢谢

修改 似乎使用dt值作为关键是一个好主意,但我仍然认为通过dt检查in_array值可以更轻松地实现相同的结果。

感谢@ArtisiticPhoenix,这段代码现在运行得很好:

    $new = [];
    foreach ($data as $k => $v) {
        $new[$v['dt']] = $v;
    }

    $Date = new DateTime();
    $days = [];
    for ($i = 0; $i < 7; ++$i) {
        $days[$Date->format('Y-m-d')] = [
            'vws' => 0,
            'mss' => 0,
            'dt'  => $Date->format('Y-m-d')
        ];
        $Date->modify('-1 days');
    }
    $final = array_merge($days, $new);

1 个答案:

答案 0 :(得分:1)

首先使用空值构建每天的数组

 //current date
$Date = new DateTime();

$days = array();
 //loop 7 times, seven days in the week  ( forget if it should be <= ) 7s to high for me to count in my head right now. :)~
for($i = 0; $i<7; ++$i ){
    $days[$Date->format('Y-m-d')] = array(
        'vws' => 0,
        'mss' => 0,
        'dt' => $Date->format('Y-m-d')  
    );
    //subtract 1 day from today's date.
    $DateTime->modify('-1 days');
}

接下来,使用array_merge将其与db数据

合并
 $data = array_merge( $days, $dbDays );

请注意,准备好的数组中的键是日期。您还希望将其添加到db填充数据中,这使得array_merge会替换这些值而不是附加条目(就像它们只是编号索引一样)。无论如何,它使数据更容易关联

或者你可以在db的while循环中添加它们,就像这样

while( false !== ( $row = $stmt->fetch() ) ){
    $days[$row['dt']] = $row;
}

但我不确定数据来自何处(mysql_ mysqli_ PDO)