Should i remove the leading "0" when sending PHP array to Json?

Björn C :

My project is to create a bar chart with "Chart.Js".

The chart should show records based on all weeks in a year. The data comes from a datetime column in MySQL.

This is how i do it:
First my select in MySQL: $query = "SELECT datetime_start FROM table WHERE datetime_start LIKE '2020%' ORDER BY datetime_start ASC";

Now i have records like: 2020-03-12 09:38:00

To group the dates into weeks i do this:

while($row = $stmt->fetch()){

    $date = new DateTime($row['datetime_start']);
    $week = $date->format("W");

    $data[$week]++;
}

And from this i send it to JS with: echo json_encode($data);

In the JS i do a console.log(result) and i get a list where the key represent the week and the value is how many dates i have in that week.

This is where my problem accours!
The list is sorted:

{10: 42, 11: 40, 12: 40, 13: 44, 14: 26, 15: 33, 16: 27, 17: 31, 18: 21, 19: 21, 20: 20, 21: 22, 22: 25, 23: 22, 24: 19, 25: 7, 26: 9, 27: 6, 28: 1, 29: 6, 30: 5, 31: 7, 32: 1, 33: 5, 34: 5, 35: 6, 36: 4, 37: 2, 38: 2, 39: 4, 40: 2, 41: 3, 42: 2, 43: 3, 44: 3, 45: 3, 46: 2, 47: 2, 48: 6, 49: 4, 50: 4, 51: 2, 52: 2, 53: 1, 01: 23, 02: 25, 03: 34, 04: 43, 05: 31, …}

Week 10 comes before week 01. And this will result in my chart looking like this:

enter image description here

Wich way is the best to solve this?

I have checked the Php.net for a datetime object that doesn't have a leading zero in the week number (format('w')), but it doesn't exist.

Should i remove the leading zero with PHP or JS to solve this? I think the PHP array is correct starting with 01, but when i decode it to Json, the order changes and 10 will be the first key in the object?!

EDIT

My PHP looks fine:

Array ( [01] => 23 [02] => 25 [03] => 34 [04] => 43 [05] => 31 [06] => 37 [07] => 32 [08] => 34 [09] => 45 [10] => 42 [11] => 40 [12] => 40 [13] => 44 [14] => 26 [15] => 33 [16] => 27 [17] => 31 [18] => 21 [19] => 21 [20] => 20 [21] => 22 [22] => 25 [23] => 22 [24] => 19 [25] => 7 [26] => 9 [27] => 6 [28] => 1 [29] => 6 [30] => 5 [31] => 7 [32] => 1 [33] => 5 [34] => 5 [35] => 6 [36] => 4 [37] => 2 [38] => 2 [39] => 4 [40] => 2 [41] => 3 [42] => 2 [43] => 3 [44] => 3 [45] => 3 [46] => 2 [47] => 2 [48] => 6 [49] => 4 [50] => 4 [51] => 2 [52] => 2 [53] => 1 )

It's the Json who gets messy:

{10: 42, 11: 40, 12: 40, 13: 44, 14: 26, 15: 33, 16: 27, 17: 31, 18: 21, 19: 21, 20: 20, 21: 22,…}
Barmar :

Don't use an associative array, use an indexed array. Start by creating an array with 53 elements, then update it in the loop.

$data = array_fill(0, 53, 0);
while($row = $stmt->fetch()){

    $date = new DateTime($row['datetime_start']);
    $week = $date->format("W");

    $data[intval($week)]++;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302229&siteId=1