gpt4 book ai didi

php echo json_encode from DB entries -> 获取奇怪的格式。如何获得正确的 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:36 27 4
gpt4 key购买 nike

此时我得到以下 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();
?>

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

最佳答案

换行

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

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

希望这对您有所帮助。

关于php echo json_encode from DB entries -> 获取奇怪的格式。如何获得正确的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50854884/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com