我如何使用json_encode()函数与MySQL查询结果?我是否需要遍历这些行,或者我可以将其应用到整个结果对象?


当前回答

我们可以这样简化Paolo Bergantino的答案

$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));

其他回答

我们可以这样简化Paolo Bergantino的答案

$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
<?php

define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', 'dishant');

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect(HOST, USER, PASS, DB);

$sql = "select * from demo ";
$sth = mysqli_query($con, $sql);
$rows = array();
while ($r = mysqli_fetch_array($sth, MYSQLI_ASSOC)) {
    $row_array['id'] = $r;

    array_push($rows, $row_array);
}
echo json_encode($rows);

array_push(行,row_array美元);有助于构建数组,否则将给出while循环中的最后一个值。

这类似于Java中StringBuilder的append方法。

使用FOR循环的另一个选项:

 $sth = mysql_query("SELECT ...");
 for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
 print json_encode($rows);

唯一的缺点是循环for比while或特别是foreach慢

根据我的经验,在命名根元素之前,上述方法是行不通的 数组中的东西,我还没有能够访问任何东西 最后的json。

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows['root_name'] = $r;
}
print json_encode($rows);

这应该能奏效!

if ($result->num_rows > 0) {
    # code...
    $arr = [];
    $inc = 0;
    while ($row = $result->fetch_assoc()) {
        # code...
        $jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
        $arr[$inc] = $jsonArrayObject;
        $inc++;
    }
    $json_array = json_encode($arr);
    echo $json_array;
} else {
    echo "0 results";
}