0

我用这个 php 代码创建了一个 json 结构:

<?php
    include "../base.php";

            $STH = $DBH->prepare("SELECT * FROM customers");
            $STH->execute();

            $result = $STH->fetchall(PDO::FETCH_ASSOC);
            $rows = $STH->rowCount();

            $jsontext = "{";
            $jsontext .= "total: ".$rows.",";
            $jsontext .= "page: 0,";
            $jsontext .= "records: [";

            foreach($result as $key => $inner_arr) {
                $jsontext .= "{";
                foreach($inner_arr as $field_name => $field_value) {
                    $jsontext .= "{$field_name}: {$field_value}, ";
                }
                $jsontext .= "},";
            }

            $jsontext .= "]";
            $jsontext .= "}";
    echo json_encode($jsontext);
?>

主要问题是这条线$jsontext .= "{$field_name}: {$field_value}, ";

当我用“echo”打印整个脚本时,它可以工作。但是$jsontext .=它不起作用,我只收到“ null ”。

4

4 回答 4

0

尝试使用 json_encode 内置函数

json_encode

于 2013-09-01T11:27:49.383 回答
0

感谢@Satya 和@keune。

将最后一行从

echo json_encode($jsontext);

echo $jsontext;

解决问题。

于 2013-09-01T11:28:48.767 回答
0

尝试:

            $STH = $DBH->prepare("SELECT * FROM customers");
            $STH->execute();

            $result = $STH->fetchall(PDO::FETCH_ASSOC);
            $rows = $STH->rowCount();

            $jsontext['total'] = $rows;
            $jsontext['page'] = 0;

            foreach($result as $key => $inner_arr) {
                foreach($inner_arr as $field_name => $field_value) {
                    $jsontext['records'][][$field_name] = $field_value;
                }
            }
    echo json_encode($jsontext);
?>

ps 我没有测试过。

于 2013-09-01T11:30:00.240 回答
0

代替

json_encode($jsontext);

echo $jsontext;
于 2013-09-01T11:30:41.113 回答