您好,我是Android新手。我的问题出在我的json值上:

<?php

include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM textviewtable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row[] = $result->fetch_assoc())
  {
    $json = json_encode($row);
  }
}
else {
 echo "0 results";
}

echo $json;

$conn->close();
?>


JSON格式


  [
   {“ id”:“ 8”,“ ServerData”:“ ABC”,“ name”:“ xyz”,“ pincode”:“ 123456”},
   {“ id”:“ 9”,“ ServerData”:“ DEF”,“名称”:“ JHG”,“密码”:“ 654321”},
   {“ id”:“ 10”,“ ServerData”:“ GHI”,“ name”:“ KIH”,“ pincode”:“ 142536”}
  ]




每一行的Json ServerDatanamepincode对象都是相同的,但我需要每一行的ServerDatanamepincode不同。

因此,对于第一行,我想显示ServerDatanamepincode,对于第二行,我想显示ServerData1name1pincode1等。我该怎么做?

最佳答案

之所以只显示一行,是因为在每个循环中,您只是在重新定义$json变量。您需要将每一行存储在一个数组中,然后回显该行。

尝试将代码更改为:

<?php

include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM textviewtable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    $data = [];

    //output data of each row

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    echo json_encode($data);

} else {
    echo "0 results";
}

$conn->close();


希望这可以帮助!

10-02 03:26