我正在尝试以以下格式输出JSON:
[{
"category": "cONTIME",
"value": 155,
"color": "#0f9b0f"
},{
"category": "cLATE",
"value": 244,
"color": "#dd1818"
},{
"category": "cTOTAL",
"value": 399,
"color": "#0575E6"
},{
"category": "ONTIME",
"value": 60,
"color": "#0f9b0f"
},{
"category": "LATE",
"value": 58,
"color": "#dd1818"
},{
"category": "TOTAL",
"value": 118,
"color": "#0f9b0f"
}]
我正在执行的存储过程返回下表-这是SQL SERVER-我将不感兴趣的列涂成灰色
我尝试使用
$categories = [
'cONTIME' => $row['cONTIME'],
'cLATE' => [],
'cTOTAL' => [],
];
$colors = [
'ONTIME' => "#0f9b0f",
'LATE' => "#dd1818",
'TOTAL' => "#0575E6",
];
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$json['category'] = $categories;
$json['value'] = $row;
$json['color'] = $colors;
}
echo json_encode($json);
返回此:
{
"category":{
"cONTIME":null,
"cLATE":[
],
"cTOTAL":[
]
},
"value":{
"cTOTAL":399,
"cONTIME":155,
"cLATE":244,
"cPERCENTS":38,
"TOTAL":118,
"ONTIME":60,
"LATE":58,
"PERCENTS":50,
"KPI":"UP"
},
"color":{
"ONTIME":"#0f9b0f",
"LATE":"#dd1818",
"TOTAL":"#0575E6"
}
}
我也尝试过这种方法:
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$json[] = $row;
}
echo json_encode($json);
返回:
[
{
"cTOTAL":399,
"cONTIME":155,
"cLATE":244,
"cPERCENTS":38,
"TOTAL":118,
"ONTIME":60,
"LATE":58,
"PERCENTS":50,
"KPI":"UP"
}
]
和上面一样,我尝试了许多其他方法和示例,但似乎无法实现我需要的格式。我完全了解PDO,Prepared Statements,Injection等!,我只需要首先格式化JSON,但在此先感谢您的建议
任何帮助将不胜感激-PHP Noob
答案 0 :(得分:1)
类似的事情应该起作用:
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
foreach ($row as $fieldName => $fieldValue) {
if (in_array($fieldName, ['cTOTAL', 'cONTIME', 'cLATE', 'TOTAL' ,'ONTIME', 'LATE'])) {
$json[] = [
"category" => $fieldName,
"value" => $fieldValue,
"color" => getColorByFieldName($fieldName),
];
}
}
}
echo json_encode($json);
function getColorByFieldName($fieldName)
{
if ($fieldName === 'ONTIME' || $fieldName === 'cONTIME') {
return '#0f9b0f';
}
if ($fieldName === 'LATE' || $fieldName === 'cLATE') {
return '#dd1818';
}
if ($fieldName === 'TOTAL' || $fieldName === 'cTOTAL') {
return '#0575E6';
}
}