2010-09-17 92 views
3

我知道這個問題毫無疑問地被問了很多次。我似乎可以找到解決辦法。所以請原諒我,如果它是簡單的方式。如何使用逗號組合數組中的所有元素?

問題是如何訪問while循環的結尾。

E.g.

while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
      $c = $countByMonth["COUNT(id)"]; 
      echo $c . "," ; 
     } 

如何以逗號分隔while循環的每個值,當然我不希望逗號在值的末尾。

在事先非常感謝你的幫助:)

回答

6

您可以:

1)建立一個字符串,刪除最後一個字符:

$c = ''; 
while ($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c .= $countByMonth["COUNT(id)"] . ','; 
} 

$c = substr($c, 0, -1); 
echo $c; 

2)建立一個數組,並使用implode()

$c = array(); 
while ($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c[] = $countByMonth["COUNT(id)"]; 
} 

echo implode(',', $c); 

提示:您可以在查詢中使用別名,如:SELECT COUNT(id) as count FROM ...。那麼你可以訪問它作爲$countByMonth['count'],看起來更清潔IMO。

+0

非常感謝,我去了很好的implode方法。感謝關於別名的提示。 – nickifrandsen 2010-09-17 12:30:35

+0

更新您的提示:$ countByMonth ['count']爲$ countByMounth ['COUNT(id)'],無論哪種方式很好的答案。 – Chris 2010-09-17 19:09:33

5

簡單解決方案:

$isFirst = true; 
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c = $countByMonth["COUNT(id)"]; 
    if ($isFirst) { 
     $isFirst = false; 
    } else { 
     echo = ', '; 
    } 
    echo $c; 
} 

或者,你可以implode()值。或者, - 也許更容易閱讀/理解/維護 - 這一切連接成一個字符串,刪除最後一個「,」(SO吃我的空白;其字符串是逗號或空格):

$list = ''; 
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c = $countByMonth["COUNT(id)"]; 
    $list .= $c . ', '; 
} 
echo substring($list, 0, -2); // Remove last ', ' 

(其他幾個答案建議使用累加數組然後使用implode()從性能角度來看,這種方法將優於字符串連接。)

請參閱註釋。

+0

你將如何調用第一個解決方案「簡單」是超越我。 – quantumSoup 2010-09-17 12:25:54

+0

@quantumSoup :)我想你是對的。它似乎在我的腦海中非常簡單......當我編寫它時非常冗長:-S – jensgram 2010-09-17 12:27:25

+0

@quantumSoup也許如果我將「簡單」定義爲*,只對您已有的內容進行一些修改,但可能不是您想要的 – jensgram 2010-09-17 12:33:07

3

或者你可以這樣做:

$arr = array(); 
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $arr[] = $countByMonth["COUNT(id)"]; 
} 

echo implode(', ',$arr); 
+1

'$ arr = $ countByMonth [「COUNT(id)」]'應該是'$ arr [] = ...' – 2010-09-17 12:24:08

+0

@jens這是錯的 – quantumSoup 2010-09-17 12:33:06

+0

@quantumSoup我看到了。 – jensgram 2010-09-17 12:33:53

2

還是後來才與RTRIM修剪其關閉($ C,」, ')

-2

泰這樣的:

int count;// 

while(i) 
{ 
    count=i; 
} 
0

雖然我認爲破滅的解決方案可能是最好的,在情況下,您可以' t使用implode,不同的思考基本算法。而不是「我怎麼能在每個元素後面添加一個逗號,但最後?」問問你自己:「除了第一個元素之外,我怎樣才能在每個元素之前加一個逗號?」

$str = ''; 
$count = count($array); 
if($count) { 
    $i = 0; 
    $str = $array[$i]; 
    $i++; 
    while(i < $count) { 
    $str .= ','.$array[$i]; 
    $i++; 
    } 
} 

如果「轉移」的第一個元素,那麼你就可以使用foreach循環:

$str = ''; 
if(count($array)) { 
    $str = array_shift($array); 
    foreach($array as $element) { 
    $str .= ', '.$element; 
    } 
} 
相關問題