2011-11-24 31 views
0

我在做什么错在这里?MySQL的结果的一个数组...

我试图返回一个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++; 
    } 

回答

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, 
       ); 

(另外,我刚刚冒昧respace这一点以提高可读性。)

要将数组转换成JSON,它传递给json_encode()

更新:哦,在你问起它之前,我只注意到在数组中的最后一项后面加了一个逗号。它看起来不合适,但在定义数组时确实存在。它没有任何特殊用途,但它允许您复制/粘贴/删除阵列中的行,而无需担心是否添加/删除尾随逗号。另外,您不必手动增加数字数组索引$i。如果你这样做:

$post_array[] = array(...); 

它会自动分配下一个可用的数字索引。

+0

这和M_M的一样好用 –

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。

例如

echo json_encode($post_array); 

你不能建立一个数组你跟$rows[...]的方式,你需要使用array。另外,您也可以使用array_push

+0

这和Wiseguy的回答一样好,谢谢! –