显示带有数组位置的json数组

时间:2016-12-31 12:37:23

标签: php mysql arrays json

您好我是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”, “名称”: “XYZ”, “pin码”: “123456”},    { “ID”: “9”, “ServerData”: “DEF”, “名称”: “JHG”, “pin码”: “654321”},    { “ID”: “10”, “ServerData”: “GHI”, “名称”: “KIH”, “pin码”: “142536”}   ]

Json ServerDatanamepincode对象在每一行都相同,但我需要每行ServerDataname和{{1}变得与众不同。

因此,对于第一行,我要显示pincodeServerDataname,第二行我要显示pincodeServerData1name1等。我该怎么做?

1 个答案:

答案 0 :(得分:0)

它只显示一行的原因是因为在每个循环中你只是重新定义$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();

希望这有帮助!