我在这里做错了什么?
我试图返回一个json对象,我似乎无法通过数组...我已经构建了数百个常规数组并将它们作为json对象返回但是我很难缠绕我的脑袋围绕这一个。
$rows = array();
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] = $rows[ "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate ];
$i++;
}
答案 0 :(得分:2)
看起来你的意思是为$post_array[$i] = ...
定义一个数组。喜欢这个?
$post_array[$i] = array(
"id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate,
);
(另外,为了便于阅读,我只是为了节省空间。)
要将数组转换为JSON,请将其传递给json_encode()
。
更新:哦,在你问起之前,我只是注意到我在数组中的最后一项之后添加了一个逗号。看起来它不合适,但在定义数组时将它放在那里实际上很好。它没有任何特殊用途,但它允许您从数组中复制/粘贴/删除行,而不必担心是否添加/删除尾随逗号。
另外,您不必手动递增数值数组索引$i
。如果你这样做:
$post_array[] = array(...);
它会自动分配下一个可用的数字索引。
答案 1 :(得分:1)
你的意思是做这样的事情:
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] =array( "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate );
$i++;
}
然后,您只需使用json_encode
将数组编码为json。
e.g。
echo json_encode($post_array);
您无法像$rows[...]
那样构建数组,您需要使用array。此外,您可以使用array_push