2015-09-29 87 views
1

我有一個foreach循環,可以回顯用戶從複選框中做出的所有選擇。將foreach循環的輸出存儲到一個變量中

我想將值存儲到名爲$getCentralArea的變量中。但是,當我回顯$getCentralArea時,它顯示4 - 只顯示所選複選框的最後一個值。我應該得到的正確值是1,2,3,4

if(!empty($_POST['centralArea'])) 
{ 
    foreach($_POST['centralArea'] as $centralArea) 
    { 
     $getCentralValue = $centralArea.","; //Output will be in the following format 1,2,3,4 
    } 
}else{ $getCentralArea="";} 
+0

使用這種$ getCentralValue打印出來= $ centralArea 「」。用於字符串或創建數組。 –

+0

使用$ getCentralValue []創建所有元素的數組。 –

回答

1

你可以串連但是留下了一個尾隨的逗號。此外,無需環路,只是implode()數組:

$getCentralValue = implode(',', $_POST['centralArea']); 
0

您需要使用.(或.=)運算符來連接你的$centralArea s到$getCentralValue,否則,它只是覆蓋$getCentralValue你每次循環:

if(!empty($_POST['centralArea'])) 
{ 
    foreach($_POST['centralArea'] as $centralArea) 
    { 
     $getCentralValue .= $centralArea.","; //Output will be in the following format 1,2,3,4 
    } 
    $getCentralValue = rtrim($getCentralValue, ","); 
} else{ $getCentralArea=""; } 
0

嘗試這樣的:使用破滅。

要麼

$result=implode(",",$_POST['centralArea']);//Output will be in the following format 1,2,3,4 

或這種情況下,你不想要的變量後直接使用。

 $getCentralValue=array(); 
     foreach($_POST['centralArea'] as $centralArea) 
     { 
      $getCentralValue[]= $centralArea; 
     } 

     $result=implode(",",$getCentralValue);//Output will be in the following format 1,2,3,4 

    echo $result; 
0

我寧願把他們在陣中,再使用爆

if(!empty($_POST['centralArea'])) 
      { 
       $stack = array(); 
       foreach($_POST['centralArea'] as $centralArea) 
       { 
        array_push($stack,$centralArea); 
       } 
//print in 1,2,3,4 
$comma_separated = implode(",", $stack); 

echo $comma_separated; 

      } 
相關問題