[英]getting json object instead of json array in php
I want the result for the json_encode()
as an array for example this: 我想要json_encode()
的结果作为数组,例如:
[
{
"url":"http://localhost/.....",
"name":"abc"
},
{
"url":"http://localhost/.....",
"name":"xyz"
},
]
But I'm getting the result as an object as this : 但是我得到的结果是这样的对象:
{"images":[{"url":"http:\/\/192.168.0.100\/1.JPG","name":"abc"},{"url":"http:\/\/192.168.0.100\/2.JPG","name":"xyz"}]}
php code: php代码:
<?php
//Importing dbdetails file
require_once 'dbDetails.php';
//connection to database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
//sql query to fetch all images
$sql = "SELECT * FROM images";
//getting images
$result = mysqli_query($con,$sql);
//response array
$response = array();
$response['images'] = array();
//traversing through all the rows
while($row = mysqli_fetch_array($result)){
$temp = array();
$temp['url']=$row['url'];
$temp['name']=$row['name'];
array_push($response['images'],$temp);
}
//displaying the response
echo json_encode($response);
I have tried using array_values as this: 我已经尝试过使用array_values这样:
echo json_encode(array_values($response));
But it results in an html code appended before the json string... 但这会导致在json字符串之前附加一个html代码...
You need to do it like this:- 您需要这样做:
$response = array();
//$response['images'] = array(); not needed
//traversing through all the rows
while($row = mysqli_fetch_assoc($result)){ //since you are using name indexes so use _assoc()
$temp = array();
$temp['url']=$row['url'];
$temp['name']=$row['name'];
$response[] =$temp;
}
//displaying the response
echo json_encode($response);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.