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.
更多推荐
发布评论