0

I wanted to make a JSON file using data from my MySql Database.

I'm using the following code to make a json file.

<?php

 $con = mysqli_connect('localhost','root','','mydb1');
 $return_arr = array();
 $sql = "select * from questions";
 $res = mysqli_query($con,$sql);
 while($row = mysqli_fetch_assoc($res)){
 $row_array['id'] = $row['id'];
 $row_array['ques'] = $row['ques'];
 $row_array['ans'] = $row['ans'];
 array_push($return_arr,$row_array);
 }
 mysqli_close($con);
 $b = json_encode($return_arr);
 $f = fopen("test.json","w");
 fwrite($f,$b);
 fclose($f);


?>

It is giving me the following output :

[{"id":"1","ques":"New Delhi is capital of India?","ans":"1"},{"id":"2","ques":"India has 5 neighboring countries.","ans":"0"}]

But i want my result to like :

{"questions" : {"question" : [{"id":"1","ques":"New Delhi is capital of India?","ans":"1"},{"id":"2","ques":"India has 5 neighboring countries.","ans":"0"}]}

So that i can use it properly in android.How can i do this? Can anyone please help?

Or can you please help me in how can i use it in android without changing my array.

Thanks in advance.

1 Answer 1

4

It's simple just change this line

$b = json_encode($return_arr);

to this line

$b = json_encode(['questions' => ['questions' => $return_arr]]);

When you were saving to JSON file you were saving as array ob objects when you want to save it as a key value pair then you have to specify the key.

Also a quick tip if you want your JSON pretty output you can use JSON_PRETTY_PRINT as your second parameter like this

$b = json_encode(['questions' => $return_arr], JSON_PRETTY_PRINT);

see here http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-parameters

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please check my edited question i changed it a bit. I need a little bit different JSON. Thanks
Thanks a lot. You saved my day. :)

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.