数组值以字符串形式存储在会话中。

数组值以字符串形式存储在会话中。

问题描述:

I have an array and it looks like this.

[cuisine] => Array
        (
            [0] => 36
            [1] => 12
            [2] => 2
            [3] => 4
            [4] => 41
            [5] => 22
        )

So now I need to store these values in SESSION. Something like this

$_SESSION['cuisine'] = 36, 12, 2, 4, 41, 22

This is how I tried it, But it doesn't work for me.

if (isset($_POST['cuisine'])) { 
    $cuisine = $_POST['cuisine']; 
    $noCuisine = count($cuisine);

    if($noCuisine >= 1) {

        $cuisines = '';
        for($i=0; $i < $noCuisine; $i++) {
            $cuisines .= $noCuisine[$i] . ", ";

        }
        echo $cuisines;

        $_SESSION['cuisines'] = $cuisines;
    } else {
        $error_alert[] = "Please select at least one Cuisine.";
    }
} else {
    $error_alert[] = "Cuisine field can NOT be empty";
}   

Can anybody tell me whats the wrong with this? Thank you

我有一个数组,它看起来像这样。 p>

  [cuisine] =&gt; 数组
(
 [0] =&gt; 36 
 [1] =&gt; 12 
 [2] =&gt; 2 
 [3] =&gt; 4 
 [4] =&gt; 41 \  n [5] =&gt; 22 
)
  code>  pre> 
 
 

所以现在我需要将这些值存储在 SESSION code>中。 像这样的东西 p>

$ _ SESSION ['cuisine'] = 36,12,2,4,41,22 code> p>

这是我尝试的方式,但它对我不起作用。 p>

  if(isset($ _ POST ['cuisine'])){
 $ cuisine = $ _POST ['cuisine'];  
 $ noCuisine = count($ cuisine); 
 
 if if($ noCuisine&gt; = 1){
 
 $ cuisines =''; 
 for($ i = 0; $ i&lt; $ noCuisine  ; $ i ++){
 $ cuisines。= $ noCuisine [$ i]。  “,”; 
 
} 
 echo $ cuisines; 
 
 $ _SESSION ['cuisines'] = $ cuisines; 
} else {
 $ error_alert [] =“请选择至少一道菜。  “; 
} 
}其他{
 $ error_alert [] =”菜系字段不能为空“; 
} 
  code>  pre> 
 
 

任何人都可以告诉我 这有什么不对吗? 谢谢你 p> div>

$noCuisines[$i] is wrong. $noCuisines is a number, not an array. It should be $_POST['cuisine'][$i].

But that whole loop is unnecessary, since PHP provides a built-in function implode for doing this.

$cuisines = implode(', ', $_POST['cuisine']);

You could also just store the array in the session variable, rather than converting it to a string:

$_SESSION['cuisines'] = $_POST['cuisine'];

Make sure you call session_start()

Use $_SESSION['cuisine'] = implode(',', $cuisine) instead of these statements:

$cuisines = '';
for($i=0; $i < $noCuisine; $i++) {
      $cuisines .= $noCuisine[$i] . ", ";

}
echo $cuisines;
$_SESSION['cuisines'] = $cuisines;