时间:2021-07-01 10:21:17 帮助过:12人阅读
$result = [
['month'=>08,'price'=>218],
['month'=>12,'price'=>140],
];
//先构造类似 ['01'=>0,'02'=>0 .... '12'=>0] 这种格式的数组
$fullMonth = [];
for($i=1;$i<=12;$i++){
$fullMonth[str_pad($i,2,'0',STR_PAD_LEFT)] = 0;
}
// 遍历数组 对应月份有值就放到新建的数组里
$i = 0;
foreach($fullMonth as $month=>$value){
foreach($result as $record){
if($month == $record['month']){
$fullMonth[$month] = $record['price'];
}
}
$i++;
}
return '[' . implode(',',$fullMonth) . ']';
$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]
$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
}
]