【问题标题】:getting json object instead of json array in php在php中获取json对象而不是json数组
【发布时间】:2017-12-16 13:07:13
【问题描述】:

我希望将 json_encode() 的结果作为一个数组,例如:

[
   {
      "url":"http://localhost/.....",
      "name":"abc"
   },
   {
      "url":"http://localhost/.....",
      "name":"xyz"
   },
]

但我得到的结果是这样的一个对象:

{"images":[{"url":"http:\/\/192.168.0.100\/1.JPG","name":"abc"},{"url":"http:\/\/192.168.0.100\/2.JPG","name":"xyz"}]}

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

我尝试过这样使用 array_values:

 echo json_encode(array_values($response));

但它会导致在 json 字符串之前附加一个 html 代码...

【问题讨论】:

  • 我看这里没问题..如果你打印youJSONObject['images']的值,你会得到你想要的结果。

标签: php android mysql arrays json


【解决方案1】:

你需要这样做:-

 $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);

【讨论】:

  • 您是否知道如何按字段“id”的降序获取数组中的内容?
  • 请通过显示您的输入数组以及您尝试了哪些代码来获得所需的输出来提出一个新问题。谢谢
猜你喜欢
  • 2020-03-01
  • 2021-12-13
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
相关资源
最近更新 更多