适用于PHP的JSON格式

时间:2016-03-31 10:46:22

标签: php mysql json mysqli

我在PHP中生成适当的JSON输出可能有一个简单的问题。我使用以下代码从mysql数据库中收集相关数据。

<?php
header('Content-Type: application/json');
$mysqli = new mysqli("localhost", "root", "", "civitas");
if (!$mysqli->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
        exit();
 }
$events = array();

if ($result = $mysqli->query("SELECT title_hu FROM `events`")) {
    while ($row = $result->fetch_assoc()) {
        $events[] = $row;
    }
    echo json_encode($events, JSON_PRETTY_PRINT);
}
$result->close();
$mysqli->close();

代码生成以下输出:

[
    {
        "title_hu": "Zr\u00ednyi napok s",
        "created_at": "2015-08-31 16:26:23"
    },
    {
        "title_hu": "Persona Non Grata 25. sz\u00fclet\u00e9snapi koncert",
        "created_at": "2015-08-31 18:12:25"
    },
    {
        "title_hu": "Bek\u00f6lt\u00f6z\u0151s buli",
        "created_at": "2015-08-31 18:22:29"
    },
    {
        "title_hu": "as",
        "created_at": "2015-08-31 18:29:13"
    },
    {
        "title_hu": "dddd",
        "created_at": "2015-08-31 18:29:58"
    }
]

但对于我使用的工具,格式应为:

{
    "events":[{
            "title_hu":"Teszt hír",
            "content":" lorembalblalba ",
            "created_at":"2015-08-31 18:29:58"
        },
        {
            "title_hu":"Teszt hír2",
            "content":" lorembalblalba ",
            "created_at":"2015-08-31 18:29:58"
        },
        {
            "title_hu":"Teszt hír3",
            "content":" lorembalblalba ",
            "created_at":"2015-08-31 18:29:58"
        }
    ]
}

我尝试将结果放入另一个数组,但在这种情况下,JSON输出只返回数据集的第一项。

我做错了什么?

2 个答案:

答案 0 :(得分:3)

首先将您的查询更改为

SELECT title_hu,content,created_at FROM `events`

用于创建JSON使用

$rows = array();// define array
$events = array();// define array
while ($row = $result->fetch_assoc()) {
        $events[] = $row;// assign table data to array
    }
$rows['events'] = $events;// assign your table data and array to an empty array
echo json_encode($rows, JSON_PRETTY_PRINT);// your final JSON

答案 1 :(得分:0)

<?php
header('Content-Type: application/json');
$mysqli = new mysqli("localhost", "root", "", "civitas");
if (!$mysqli->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
        exit();
}
$events = array('events'=>array());

if ($result = $mysqli->query("SELECT title_hu, content, created_at FROM `events`")) {
    while ($row = $result->fetch_assoc()) {
        $events['events'][] = $row;
    }
    echo json_encode($events, JSON_PRETTY_PRINT);
}
$result->close();
$mysqli->close();

这应该可以解决问题。