2011-02-04 132 views
0

我有這個在PHP嵌套JSON在PHP

$comment = array; 
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){ 
    $comment[$row['name']] = $row['comment']; 
} 
echo json_encode($comment); 

Having these results 
{"John":"Yo","Dan":"Hello","May":"Bye"} 

問題是,我實際上有兩個意見(ZUP,喲)爲約翰,但你可以看到,它只是顯示約翰的最後一個註釋這是「喲」。所以我想約翰的結果是

{"John":["Yo","Sup"]} 

^這可能嗎?

我該怎麼做?對不起,仍然很難處理JSON。由於

這其實是我的全部代碼

while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){ 
    $comment[$row['name']] = $row['comment']; 

    $sql_dup = "SELECT name, COUNT(name) AS dup_count 
         FROM comment 
         GROUP BY name 
         HAVING (COUNT(name) > 1) 
       "; 
    $sqlExec_dup = mysql_query($sql_dup, $connection); 
    $row_dup = mysql_fetch_array($sqlExec_dup, MYSQL_ASSOC); 
    if($row['name'] = $row_dup['name']){ 

     $sql_dup2 = "SELECT * FROM comment WHERE name = '{$row['name']}'"; 
     $sqlExec_dup2 = mysql_query($sql_dup2, $connection); 
     while($row_dup2 = mysql_fetch_array($sqlExec_dup2, MYSQL_ASSOC)){ 
      $x += 1; 
      if($x <= $row_dup['dup_count']){ 
       $comment[$row['name']][] = $row_dup2['comment']; 
      } 
     } 
    } 
} 

如果名稱有重複的,這意味着它有一個以上的評論,斜面還是讓我想要的結果。

回答

2

你必須檢查它是否已經存在與否,如果是的話,創建一個數組(或做,結果從開始)

// Create arrays with names 
$comment[$row['name']][] = $row['comment']; 

// Check if there's an array 
if (isset($comment[$row['name']])) { 
    if (is_array($comment[$row['name']])) { 
     $comment[$row['name']][] = $row['comment']; 
    } else { 
     $comment[$row['name']] = array($comment[$row['name']], $row['comment']); 
    } 
} else { 
    $comment[$row['name']] = $row['comment']; 
} 

我要指出因爲第一個解決方案會非常受歡迎,因爲它會帶來更多的後果。

0

是的,這是可能的。取而代之的這條線:

$comment[$row['name']] = $row['comment']; 

使用此:

$comment[$row['name']] = array('Yo', 'Sup'); 

,代之以從數據庫所需的問候數組的內容。

0

簡單的變化:

$comment[$row['name']] = $row['comment']; 

$comment[$row['name']][] = $row['comment']; 

的$評論陣列中的每個name元素正在各同名上前時被覆蓋。

1

是的,這是可能的,但你需要做一些預處理:

$comment = array; 
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){ 
    if(!isset($comment[$row['name']])) { 
    $comment[$row['name']] = array(); 
    } 
    $comment[$row['name']][] = $row['comment']; 
} 
echo json_encode($comment); 
+0

謝謝,現在弄明白了:d – Barry 2011-02-04 19:54:12