【发布时间】:2013-09-01 11:23:51
【问题描述】:
我用这个 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”。
【问题讨论】:
-
json_encode 是一个将php数组转换为json字符串的函数,你不需要在foreach中做任何这些
-
只需使用 echo $jsontext;