如何在php中的简单数组中包含关联数组?

时间:2022-04-15 08:29:45

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

我想用MySql数据库中的数据创建一个JSON文件。

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

我正在使用以下代码创建一个json文件。

<?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?

这样我就可以在android中正确地使用它了。我该怎么做呢?谁能请帮助?

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

或者你可以帮助我,我如何在android中使用它而不改变我的数组。

Thanks in advance.

提前谢谢。

1 个解决方案

#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.

当你保存到JSON文件时,你保存为数组ob对象,当你想要保存为键值对时,你必须指定键。

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

还有一个快速提示,如果您想要JSON漂亮的输出,可以使用JSON_PRETTY_PRINT作为第二个参数,如下所示

$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

看到http://php.net/manual/en/function.json-encode.php refsect1-function.json-encode-parameters

#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.

当你保存到JSON文件时,你保存为数组ob对象,当你想要保存为键值对时,你必须指定键。

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

还有一个快速提示,如果您想要JSON漂亮的输出,可以使用JSON_PRETTY_PRINT作为第二个参数,如下所示

$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

看到http://php.net/manual/en/function.json-encode.php refsect1-function.json-encode-parameters