看看這個回圈
$dataPoints1 = array();
$dataPoints2 = array();
$sql = "SELECT DATE_FORMAT(date,'%M') as 'date', income, expense FROM `balance` group by DATE_FORMAT(date,'%m');";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($dataPoints1, $row); **desire one - to push into $dataPoints1 array from $row**
array_push($dataPoints2, $row); **desire two - to push into $dataPoints2 array from $row**
}
}
我的桌子,
| ID | 日期 | 收入 | 費用 |
|---|---|---|---|
| 1個 | 2022-05-01 00:00:00 | 20 | 10 |
| 2個 | 2022-06-01 00:00:00 | 40 | 30 |
| 3個 | 2022-07-01 00:00:00 | 60 | 50 |
在一個愿望中,我想像這樣從關聯陣列 ($row) 中推送帶有特定列的自定義鍵和值,
$row
↓
{"label":"date","y":"income"}
在也渴望兩個,
$row
↓
{"label":"date","y":"expense"}
最終輸出如下,
dataPoints1
↓
[{"label":"May","y":"20"},{"label":"June","y":"40"},{"label":"July","y":"60"}]
dataPoints2
↓
[{"label":"May","y":"10"},{"label":"June","y":"30"},{"label":"July","y":"50"}]
我會用 json_encode 回應,
echo json_encode($dataPoints1);
echo json_encode($dataPoints2);
uj5u.com熱心網友回復:
更好的變數命名將有助于使您的代碼更清晰。
Mysqli 結果集物件可以被迭代,foreach()就好像它們是關聯陣列的陣列一樣。
$income = [];
$expenses = [];
foreach ($conn->query($sql) as $row) {
$income[] = ['label' => $row['date'], 'y' => $row['income']];
$expenses[] = ['label' => $row['date'], 'y' => $row['expense']];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535066.html
