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 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密