来自数据库条目的php echo json_encode - >得到奇怪的格式。如何获得正确的JSON

时间:2018-06-14 10:05:58

标签: php mysql json

目前我得到以下JSON:

["1Sales & Consulting","2Pyments","3Investing","4Financing","5Cross Functional"]

但我希望有一个合适的JSON,如:

[{"id":1, "name": "Sales & Consulting"}{"id": 2, "name": "Pyments"}{"id": 3, "Investing"}{"id": 4, "name": "Financing"}{"id": 5, "name": "Cross"}] 

我用来生成第一个输出的代码是:

<?php
define('servername','localhost');
define('username','root');
define('password','');
define('dbname','integration');
// Create connection
$conn = new mysqli(servername, username, password, dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM capability_level1";
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $test[] = $row["id"] . $row["name"];
    }
    echo json_encode($test);
} else {
    echo json_encode("0 results");
}
$conn->close();
?>

我需要改变什么?这个回声需要在第二步传递给ajax

3 个答案:

答案 0 :(得分:3)

更改行

while($row = $result->fetch_assoc()) {
    $test[] = $row["id"] . $row["name"];
}

while($row = $result->fetch_assoc()) {
    $test[] = array(
         'id' => $row["id"],
         'name' => $row["name"]
    );
}

希望这有帮助。

答案 1 :(得分:1)

请改为尝试:

 while($row = $result->fetch_object()) {
       array_push($test, $row);
 }
 echo json_encode($test);

答案 2 :(得分:0)

使用以下代码更改: -

<?php
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        array_push($test, $row);
    }
    echo json_encode($test);
} else {
    echo json_encode("0 results");
}
$conn->close();

?>