I have this table, table1:
+----+-------+----------+
| ID | MONTH | QUANTITY |
+----+-------------+----+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 7 | 3 |
| 4 | 4 | 1 |
| 5 | 2 | 3 |
| 6 | 12 | 8 |
| 7 | 1 | 6 |
+----+-------+----------+
My file php is:
<?php
include 'bd_cnx.php';
$ret =[];
$sql = "SELECT
FROM
";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
//floatval() transforma sirul numeric in numar
$ret[] =[$row['MONTH'], floatval($row['QUANTITY'])];
}
}
else {
echo "result 0";
}
?>
How can I return to the values in this form? [ [1,7],[2,5],[3,0],[4,1],[5,0],[6,0],[7,3],[8,0],[9,0],[10,0],[11,0],[12,8] ]
Thank you!
You can make a temp array of your database results and then do a loop over a (fixed) set of months (1-12)
$tmp = array();
while($row = $result->fetch_assoc()){
$tmp[$row['MONTH']] = $row['QUANTITY'];
}
$retTmp = array();
for($i=1;$i<=12;$i++){
$retTmp[] = "[$i," .(isset($tmp[$i]) ? $tmp[$i] : 0) . "]";
}
$ret = '[' . implode(',', $retTmp) . ']';
Use below code.
$finalArray = $store = [];
$sql = "SELECT MONTH,SUM(QUANTITY) FROM `stack` GROUP BY MONTH";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
//floatval() transforma sirul numeric in numar
$store[$row['MONTH']] = $row['QUANTITY'];
}
$finalArray = '[';
for ($i = 1; $i <= 12; $i++) {
$finalArray .= "[$i," . (isset($store[$i]) ? $store[$i] : 0) . "]";
if ($i != 12) {
$finalArray .= ",";
}
}
$finalArray .= ']';
} else {
echo "result 0";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.