To solve the array processing problem, we need to optimize an array that is queried in this way.
$result = [['month'=>08,'price'=>218],['month'=>12,'price'=>140],];
Finally, it needs to be converted into a string for foreground js
Format: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, null, null]
Displays the monthly sales status. if there is no value, the value is null.
For example, the price in March is 49.9.
My practices:
I feel a little troublesome. I want to optimize it.
// Construct a structure similar to ['01' => 0, '02' => 0 .... '12' => 0] an array in this format $ fullMonth = []; for ($ I = 1; $ I <= 12; $ I ++) {$ fullMonth [str_pad ($ I, 2, '0', STR_PAD_LEFT)] = 0 ;} // traverse the corresponding month of the array and put it in the new array $ I = 0; foreach ($ fullMonth as $ month => $ value) {foreach ($ result as $ record) {if ($ month = $ record ['month']) {$ fullMonth [$ month] = $ record ['price'] ;}}$ I ++ ;} return '['. implode (',', $ fullMonth ). ']';
Reply to discussion (solution)
Why not use json format?
$result = [ ['month'=>08,'price'=>218], ['month'=>12,'price'=>140],];echo json_encode($result); // [{"month":0,"price":218},{"month":12,"price":140}]
New Document
08, 'price' => 218], ['month' => 12, 'price' => 140],];?>