2

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
  • 1
    i see no problem here.. if you print value of youJSONObject['images'], You'll get your desired result. Commented Jul 12, 2017 at 8:15

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Would you happen to know how could I fetch the content in the array in Descending order of the field 'id'?
Please ask a new question by showing your input array and what code you tried so for to get your desired output.Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.