PHP从数据库条目回显json

编程入门 行业动态 更新时间:2024-10-25 12:19:49
PHP从数据库条目回显json_encode - >获得奇怪的格式。(php echo json_encode from DB entries -> getting strange format. how to get a proper 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

At the moment i get the following JSON:

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

but i would like to have a proper JSON like:

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

The code i used to generate the first output is:

<?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(); ?>

what do i have to change? this echo is needed to pass to ajax in a second step

最满意答案

改变线条

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

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

希望这可以帮助。

Change the lines

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

to

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

Hope this helps.

更多推荐

本文发布于:2023-07-17 13:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条目   数据库   PHP   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!