2013-05-02 90 views
0

我试图访问一个php数组。但它是抛出我阵列字符串转换错误。PHP数组到字符串转换

这是我的代码

if(isset($_POST['category'])){ 
       $category = array($_POST['category']); 
       if(sizeof($category) > 0){ 
        foreach($category as $key){ 
         $categ = $categ.$key.', '; 
        } 
       } 
      } 
+1

$ _POST ['category']中包含了什么?一个字符串或数组? – philipobenito 2013-05-02 14:53:28

+1

'print_r()'你的变量 - 你认为其中一个字符串('$ categ','$ key')不是字符串。也初始化你的变量 - 你的下一个问题将是'$ categ is undefined'(你第一次访问它)。 – AD7six 2013-05-02 14:54:03

+0

在这种情况下,类别必须是对象数组。 $ key本身应该是一个不能转换为字符串的对象。 – hridayesh 2013-05-02 14:54:18

回答

1

做..

if (isset($_POST['category'])) { 

    if (!is_array($_POST['category'])) { 
     $category = array($_POST['category']); 
    } else { 
     $category = $_POST['category']; 
    } 

    $categ = ''; 

    foreach ($category as $value) { 
     if (!is_string($value)) { 
      // do anything, but not autocast to string! 
      continue; 
     } 
     $categ .= $value . ', '; 
    } 
} 
0

这应该做的工作。

if (is_array($_POST['category'])) { 

    $category = implode(", ", $_POST['category']); 

}