【问题标题】:How can i include an associative array in a simple array in php?如何在 php 的简单数组中包含关联数组?
【发布时间】:2017-02-27 07:20:24
【问题描述】:

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

我正在使用以下代码制作一个 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);


?>

它给了我以下输出:

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

但我希望我的结果喜欢:

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

这样我就可以在android中正确使用它了。我该怎么做呢? 有人可以帮忙吗?

或者你能帮我看看如何在不改变我的数组的情况下在 android 中使用它。

提前致谢。

【问题讨论】:

    标签: php mysql arrays json


    【解决方案1】:

    很简单,只需更改这一行

    $b = json_encode($return_arr);
    

    到这一行

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

    当您保存到 JSON 文件时,您正在保存为数组 ob 对象,当您想将其保存为键值对时,您必须指定键。

    如果您想要漂亮的 JSON 输出,也可以使用 JSON_PRETTY_PRINT 作为第二个参数,就像这样

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

    看这里http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-parameters

    【讨论】:

    • 你能检查一下我编辑过的问题吗,我改了一点。我需要一点不同的 JSON。谢谢
    • 非常感谢。你拯救了我的一天。 :)
    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 2011-04-26
    • 2018-02-02
    • 2013-02-17
    • 2011-07-26
    • 2011-09-03
    • 2012-12-11
    • 2014-01-11
    相关资源
    最近更新 更多