2 回答

TA貢獻1818條經驗 獲得超8個贊
您應該更改查詢數據庫的方式。您應該使用準備好的語句,而不是在查詢中注入字符串。這使您容易受到 sql 注入的影響。
回到問題:
對于發現的每個月,您需要創建一個數組,其中包含一個系列數組。檢查月份數組是否存在,如果它不創建它并創建系列數組。然后創建一個包含系列數據的數組,并將其中的系列數據推送到該月的系列數組中。
查看代碼要容易得多。我也添加了評論。
$result = mysqli_query($db, $query)or die(mysqli_error());
$response = array();
$posts = array();
while($row=$result->fetch_assoc())
{
$month=$row['name'];
if(!isset($posts[$month])){// Check to see if the month array exists
//if it doesn't create it
$posts[$month] = array();
//create the series array so data can be pushed to it
$posts[$month]["series"] = array();
}
//check to see if it is null and if it is make it 0
if(is_null($row['value'])){
$row['value'] =0;
}
//put the series data in the correct format with correct names
$series_array = array(
"name" => $row['facility'],
"value" => $row['value']
);
//push the series data into the months series array
array_push($posts[$month]["series"],$series_array);
}
// put months and series together
$new_posts=array();
foreach($posts as $month_name => $data){
array_push($new_posts, array("name"=> $month_name, "series"=> $data['series'] ));
}
$posts = $new_posts;
$response['data'] = array($posts);
header('Content-Type: application/json');
echo json_encode($response, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);

TA貢獻1827條經驗 獲得超9個贊
這是您需要的代碼
$result = mysqli_query($db, $query)or die(mysqli_error($db));
$response = array();
$posts = array();
while($row=$result->fetch_assoc()){
$month = $row['name'];
$value = $row['value'];
if(empty($value)){
$value = 0;
}
$series = array(
"name" => $row['facility'],
"value" => $value
);
$found_key = array_search($month, array_column($posts, 'name'));// check if month value exist in name key
if(!$found_key){//if not found
$found_key = sizeof($posts);// get the size of array which will be 1 more then last index of array
}
$posts[$found_key]['name'] = $month;// this add name of month
if(!isset($posts[$found_key]['series'])){ // check if series is set
$posts[$found_key]['series'] = array();// or set it
}
$posts[$found_key]['series'][] = $series; //assign the series array
}
$response['data'] = $posts;
header('Content-Type: application/json');
echo json_encode($response, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
- 2 回答
- 0 關注
- 165 瀏覽
添加回答
舉報