duanchuiwen6694 2017-07-12 08:11
浏览 100
已采纳

在php中获取json对象而不是json数组

I want the result for the json_encode() as an array for example this:

[
   {
      "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 

//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:

 echo json_encode(array_values($response));

But it results in an html code appended before the json string...

  • 写回答

1条回答 默认 最新

  • dongnaosuan5407 2017-07-12 08:14
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue2中使用计算属性
  • ¥50 远程桌面打开Mastercam、没有许可证、物理机打开正常
  • ¥15 ubuntu安装gdal后java读取tif文件报错
  • ¥15 请问lammps怎么做两种金属连接的原子浓度分布图
  • ¥15 求jacquard数据集
  • ¥15 w10部分软件不能联网
  • ¥15 关于安装hbase的问题(操作系统-windows)
  • ¥15 novnc连接pve虚拟机报错安全协议不支持262
  • ¥15 设备精度0.03给多少公差能达到CPK1.33
  • ¥15 qt+ffmpeg报错non-existing PPS 0 referenced