如何使用PHP在我的json文件周围创建括号?

时间:2018-01-25 00:41:44

标签: php json phpmyadmin

function get_data()
{
    $connect = mysqli_connect("localhost", "root", "root", "Database");
    $query = "SELECT * FROM Furniture";
    $result = mysqli_query($connect, $query);
    $categories = array();

    $row = mysqli_fetch_array($result);

{
        $categories[] = array(

        'mapwidth' => "2000",
        'mapheight' => "2000",


       );            
 }

这是我到目前为止所做的,但是我怎么能够创建一个“类别”数组,以便json文件看起来像这样,

{
    "mapwidth": "2000",
    "mapheight": "2000",
    "categories": [
    {
        "id": "furniture",
        "title": "furniture",
        "color": "#4cd3b8",
        "show": "false"
    },
    {
        "id": "rooms",
        "title": "Rooms",
        "color": "#63aa9c",
        "show": "true"
    }
    ],

我尝试这样做,但我只能显示一行,但不知道如何遍历数据库,以便每一行都显示“id”,“title”,“color”和“显示“在json文件中看到的括号内。所以我只是想让json文件看起来与这里显示的完全一样。

1 个答案:

答案 0 :(得分:0)

试试这样:

$employee_data = array();
$categories = array();
$employee_data["mapwidth"] ="2000";
$employee_data["mapheight"] ="2000";

while($row = $result->fetch_array(MYSQL_ASSOC)) {
        $categories[] = $row;
}
$employee_data["categories"] =$categories;
echo json_encode($employee_data);

请参阅this answer以进一步改进您的代码。