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


当前回答

考虑到在mysql中通常没有任何嵌套的json对象,创建自己的编码函数是相当容易的

首先,检索mysqli的函数会生成一个数组:

function noom($rz) {
    $ar = array();
    if(mysqli_num_rows($rz) > 0) {
        while($k = mysqli_fetch_assoc($rz)) {
            foreach($k as $ki=>$v) {
                $ar[$ki] = $v;
            }
        }
    }
    return $ar;
}

现在,函数将数组编码为json:

function json($ar) {
    $str = "";
    $str .= "{";
    $id = 0;
    foreach($ar as $a=>$b) {
        $id++;
        $str .= "\"".$a."\":";
        if(!is_numeric($b)) {
            $str .= "\"".$b."\"";
        } else {
            $str .= $b;
        }
        
        if($id < count($ar)) {
            $str .= ",";
        }
    }
    $str .= "}";
    return $str;
}

然后使用它:

<?php
$o = new mysqli(
    "localhost",
    "root",""
);
if($o->connect_error) {
    echo "DUDE what are you/!";
} else {
    $rz = mysqli_query($o,
        "SELECT * FROM mydatabase.mytable"
    );
    $ar = noom($rz);
    echo json($ar);
}
?>

其他回答

根据我的经验,在命名根元素之前,上述方法是行不通的 数组中的东西,我还没有能够访问任何东西 最后的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";
}
<?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方法。

下面的代码在这里可以正常工作!

<?php

  $con=mysqli_connect("localhost",$username,$password,databaseName);

  // Check connection
  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $query = "the query here";

  $result = mysqli_query($con,$query);

  $rows = array();
  while($r = mysqli_fetch_array($result)) {
    $rows[] = $r;
  }
  echo json_encode($rows);

  mysqli_close($con);
?>

例如 $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");

1.)如果$result只有一行。

$response = mysql_fetch_array($result);
echo json_encode($response);

2.)如果$result多于一行。你需要迭代这些行,并将其保存到一个数组中,并返回一个包含数组的json。

$rows = array();
if (mysql_num_rows($result) > 0) {
    while($r = mysql_fetch_assoc($result)) {
       $id = $r["USERID"];   //a column name (ex.ID) used to get a value of the single row at at time
       $rows[$id] = $r; //save the fetched row and add it to the array.
    }
}    
echo json_encode($rows);