好的,我有一个与此类似的东西。
<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
echo "failed to connect:" . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = while($row = mysqli_fetch_assoc($grab)){
"id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
json.encode($cars);
所以我知道while循环有点奇怪,但我需要知道如何调整代码以便我可以对结果变量进行json编码,因此我得到了一个关联数组数组。
我知道这段代码不会工作,但我怎么能让它工作,我猜它会多做一些工作,但我对编码和php很新。
任何帮助都将不胜感激,谢谢。
答案 0 :(得分:0)
$cars = array();
while($row = mysqli_fetch_assoc($grab)){
$cars[] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]);
}
json_encode($cars);
这是正确的语法和方法
答案 1 :(得分:0)
关闭?
$the_array = array();
while($row = mysqli_fetch_assoc($grab)) {
$temp = array();
$temp['id'] = $row['Id'];
$temp['name'] = $row['Name'];
$temp['color'] = $row['Color'];
$the_array[] = $temp;
}
json_encode($the_array);
答案 2 :(得分:0)
PDO
扩展名。$grab = mysql_query($con, "SELECT * FROM DB"); $cars = array(); $i = 0; while($row = mysql_fetch_array($grab)) $cars[$i++] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]); header('Content-Type: application/json'); json.encode($cars);