To solve the array processing problem, find and optimize this post. at last, mafeifan edited an array from 2014-12-2611: 36: 04. $ Result & nbsp; [[month & gt; 08, price & gt; 218], [month & gt; 12, price & gt; 140],] array processing problems, optimization
This post was last edited by mafeifan at 11:36:04
There is an array to be 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.
// First construct an array similar to ['01' => 0, '02' => 0... '12' => 0]
$ FullMonth = [];
For ($ I = 1; $ I <= 12; $ I ++ ){
$ FullMonth [str_pad ($ I, 2, '0', STR_PAD_LEFT)] = 0;
}
// Traverse the array and put the corresponding month value 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). ']';
------ Solution ----------------------
$r = array_fill(0, 12, null);
$result = [
['month'=> '08', 'price'=> 218],
['month'=> '12', 'price'=> 140],
];
foreach($result as $v) {
$r[$v['month'] - 1] = $v['price'];
}
echo json_encode($r);
[null,null,null,null,null,null,null,218,null,null,null,140]
------ Solution ----------------------
Y plus the quote, so there will be no notice
$res = [['y'=>'2014-12-03','item'=>263],['y'=>'2014-12-04','item'=>168]];
echo json_encode($res, JSON_PRETTY_PRINT);
?>
[
{
"y": "2014-12-03",
"item": 263
},
{
"y": "2014-12-04",
"item": 168
}
]