我需要获得如下所示的json格式:
<?php
include("db.php");
date_default_timezone_set('Asia/Kolkata');
$thisyear = date("Y");
$months = array();
for($i=0;$i<=12;$i++)
{
array_push($months, 0);
unset($months[0]);
}
$stack = array(
1 => 'JAN',
2 => 'FEB',
3 => 'MAR',
4 => 'APR',
5 => 'MAY',
6 => 'JUN',
7 => 'JUL',
8 => 'AUG',
9 => 'SEP',
10 => 'OCT',
11 => 'NOV',
12 => 'DEC'
);
$year[0] = 0;
$stmt = $conn1->prepare("SELECT * FROM salessummary WHERE dateoforder LIKE :key");
$stmt->execute(array('key' => "%{$thisyear}%"));
foreach ($stmt as $row) {
$month = date('m', strtotime($row['dateoforder']));
$months[intval($month)]++;
}
$high = max($months) + 10;
$datayearly = array(
'labels' => array_values($stack),
'series' => array(array(
'name' => 'series-1',
'data' => array_values($months)
))
);
$temp = json_encode($datayearly);
echo $temp;
?>
..... ... 目前我使用下面给出的代码获得的格式如下。有什么办法可以将这个JSON输出转换为上面的那个。或者我怎么能重写下面的PHP代码。因为我是php的新手,所以对我来说似乎很困惑。感谢您提前提供的宝贵帮助。
{
"labels":[
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC"
],
"data":[
0,
0,
0,
0,
0,
0,
0,
0,
1,
2,
1,
0
]
当前输出:
{{1}}
}
答案 0 :(得分:0)
尝试以下方法:
$datayearly = [];
for($i=1;$i <= count($months);$i++)
{
$datayearly[] = [
'month' => $stack[$i],
'data' => $months[$i]
];
}
这将提供输出作为month
和data
的对象。这只是使用for
循环来创建一个新数组。输出将如下:
[{
"month": "JAN",
"data": 0
}, {
"month": "FEB",
"data": 0
}, {
"month": "MAR",
"data": 0
}, {
"month": "APR",
"data": 0
},
...........
答案 1 :(得分:0)
我会用这样的东西来生成你的阵列:
$datayearly=[];
foreach(array_values($stack) as $i=> $m){
$datayearly[]['month']=$m;
$datayearly[]['data']=$array_values($months)[$i];
}