编码一个完美的json

时间:2011-12-11 07:36:26

标签: php mysql arrays json

我有这个代码

$md_query = "SELECT * FROM table ORDER BY id ASC";
$md_result = mysql_query($md_query, $con);

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');

while($md_row=mysql_fetch_array($md_result))
    $data_row = array(
        'id' => $md_row['id'],
        'type' => $md_row['type'],
        'title' => $md_row['title'],
        'content' => $md_row['content'],
        'author' => $md_row['postedby'],
        'post_date' => $md_row['posteddate'],
        'publish' => $md_row['publish']
    );

print json_encode($data_row); `

但我只显示1条记录......有人如何解决这个问题?

5 个答案:

答案 0 :(得分:5)

你的while循环不包含print语句...所以,它循环遍历所有记录,每次完全重置$data_row,然后在完成后打印一次。

要包含多个语句,您需要使用{}来封装块。

答案 1 :(得分:1)

您正在遍历数据并将$data_row设置为每行的新数组,但在退出循环之前,您没有对其执行任何操作。

答案 2 :(得分:1)

为什么要显示所有行过于复杂,或用{}换行?只需使$data_row成为一个多维数组,json_encode()就会为你做[]:

while($md_row=mysql_fetch_array($md_result))
$data_row[] = array(   // please note I added [] !
    'id' => $md_row['id']
    ,'type' => $md_row['type']
);

print json_encode($data_row);

打印例如:

[{"id":"3","type":"One"},{"id":"8","type":"Two"},{"id":"9","type":"Three"},{"id":"10","type":"Four"}]

如果将该JSON字符串转换回数组,它看起来像这样:

Array(
[0] => Array
    (
        [id] => 3
        [type] => One
    )

[1] => Array
    (
        [id] => 8
        [type] => Two
    )

[2] => Array
    (
        [id] => 9
        [type] => Three
    )

[3] => Array
    (
        [id] => 10
        [type] => Four
    ))

答案 3 :(得分:-1)

代码示例仅在循环结束后打印$data_row,此时$data_row保存结果的最后一行。您需要将行收集到数据结构中,JSON编码并打印它,或者在每次循环迭代时打印每一行。

...
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');

$md_query = $db->prepare(
    "SELECT id, type, title, content, postedby AS author, 
            posteddate AS post_date, publish
       FROM posts 
       ORDER BY id ASC");

try {
    $md_query->execute();
    echo json_encode($md_query->fetchAll(PDO::FETCH_ASSOC));
} catch (PDOException $exc) {
    ...
}

请注意,由于这会从表中获取所有行,因此可能会耗尽脚本的最大允许内存或运行时间。如果内存限制有问题,请更改负责显示结果的代码行,以便一次打印一个块。例如:

    ...
    $md_query->setFetchMode(PDO::FETCH_ASSOC);

    echo '[';
    $last = $md_query->rowCount()-1;
    foreach ($md_query as $i => $post) {
        echo json_encode($post);
        if ($i < $last) {
            echo ", ";
        }
    }
    echo ']';
} catch (PDOException $exc) {
    ...

答案 4 :(得分:-2)

您需要封装行记录,如{row1:{a:b,b:c},row2:{e:f,g:h}}

$json = '{';
while($md_row=mysql_fetch_array($md_result)) {
$data_row = array(
    'id' => $md_row['id'],
    'type' => $md_row['type'],
    'title' => $md_row['title'],
    'content' => $md_row['content'],
    'author' => $md_row['postedby'],
    'post_date' => $md_row['posteddate'],
    'publish' => $md_row['publish']
);
$json .= '"' . $id . '" :' . json_encode($data_row) . ','; 
// $id just as an example for the string-value pair
}
$json = substr($json, 0, -1); // remove comma after last row
$json .= '}';
echo $json;

有关更多示例,请参阅:

http://json.org/

http://json.org/example.html