BUG ADDER BUG ADDER -4 years ago 67
MySQL Question

How can i include an associative array in a simple array in php?

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download