简体   繁体   中英

Get count of months from given mysql result

I am trying to get the amount of users registered by month to insert it into a chart.js The problem that I am having is to display the count result per month.

I get the following results from mysql query

php print_r($this->results);

results

Array (
  [0] => Array
    (
        [d] => 2018-05-15 21:54:08
    )

  [1] => Array
    (
        [d] => 2018-05-16 15:50:58
    )

  [2] => Array
    (
        [d] => 2018-06-18 18:27:11
    )

)

The answer should be: 05=2 and 06=1

Thanks for the help!

Code

$data = [];
$data[0]['d'] = '2018-05-15 21:54:08';
$data[1]['d'] = '2018-05-16 15:50:58';
$data[2]['d'] = '2018-06-18 18:27:11';

$result = [];
foreach( $data as $element ) {
    // convert date to timestramp by strToTime
    // get month via date( 'm' )
    $month = date( 'm', strToTime( $element['d'] ) );

    // if a count for month is present increment it
    if( isset( $result[$month] )) {
        $result[$month]++;
    } else { // if NO count is present, create and set to 1
        $result[$month] = 1;
    }
}

echo '<pre>';
var_dump($result);

Result

array(2) {
  ["05"]=>
  int(2)
  ["06"]=>
  int(1)
}

Edit

added explaination

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM