2

我有一个由 MySQL 生成的数组,其中包含本周的访问者:

Array
    (
        [0] => Array
            (
                [iid] => 2
                [mid] => 123456
                [name] => Username  
                [date] => 2013-09-03 18:19:23
            )

        [1] => Array
            (
                [iid] => 2
                [mid] => 123456
                [name] => Username 
                [date] => 2013-09-03 18:19:20
            )

        [2] => Array
            (
                [iid] => 2
                [mid] => 123456
                [name] => Username  
                [date] => 2013-09-03 18:10:42
            )

    )

每个键都是一个访问者,我需要每天计算数组中有多少个访问者。

该数组应返回:

Mon: 0    
Tue: 3
Wed: 0
etc
4

1 回答 1

1

正如通过谷歌搜索和通过在 PHP 中对多维数组进行分组来查找计数所了解到的那样,我修改了代码,这似乎解决了您的问题:

$inputArray  = array(
    array('iid' => 5, 'mid' => '123456', 'name' => 'Username', 'dd'  => '2013-09-03 18:19:23'),
    array('iid' => 5, 'mid' => '123456', 'name' => 'Username', 'dd'  => '2013-09-03 18:19:20'),
    array('iid' => 5, 'mid' => '123456', 'name' => 'Username', 'dd'  => '2013-09-03 18:10:42'),
    array('iid' => 5, 'mid' => '123456', 'name' => 'Username', 'dd'  => '2013-09-04 18:19:23'),
    array('iid' => 5, 'mid' => '123456', 'name' => 'Username', 'dd'  => '2013-09-04 18:19:23'));

$outputArray = array();

foreach ( $inputArray as $record ) {

    // get only the first part of the date string i.e. 2013-09-03
    $day = explode(' ', $record['dd']);

    // if the date has not already been added to the outputArray, add it
    if ( !key_exists($day[0], $outputArray) ) {
        $outputArray[$day[0]] = 0;
    }
    $outputArray[$day[0]] += 1;
}

echo '<pre>';
print_r($outputArray);

输出:

Array
(
    [2013-09-03] => 3
    [2013-09-04] => 2
)

您可以通过在此处复制和粘贴来测试它http://writecodeonline.com/php/

于 2013-09-03T17:25:57.963 回答