如何将逗号分隔的单词放入数组

how to put comma separated words into array

我有一个数组,我已将其转换为逗号分隔,我是这样做的:

$array[] = $imp;
$strings = implode(", ", $array);

内爆后我得到 34、56、78。

现在我在会话中存储了一个数组,我想将 $strings 添加到其中,例如:

array_push($_SESSION['array'],$strings);

但是打印时我得到:

Array ( [0] => 191 [2] => 34, 56, 78 )

我想分别添加 34、56、78 值,以便数组看起来像这样:

Array ( [0] => 191 [2] => 34 [3] => 56 [4] => 78 )

要数组为什么要内爆数组?只需这样做:

$_SESSION['array'] = array_merge($_SESSION['array'], $imp);

这是适合您的解决方案。

<?php
$arr= array('5','10,20,30');
$newArr = [];
foreach ($arr as $key => $value) {    
    $element = explode(',',$value);
    if (count($element)>1) {
      echo "This is an array";
      foreach ($element as $key => $value1) {
        $newArr[]=$value1;
      }   
    } else {
      echo "Not an array";
      $newArr[]=$value;
    }
}
echo "<pre>";print_r($newArr);

?>

复制粘贴下一个代码并运行在您的浏览器中:

<html>
  <head>
  </head>
  <body>
<?php
$_SESSION[ "arr" ] = array( "100","200","300" );
$strings = "34,56,78";
$_SESSION[ "arr" ] = array_merge( $_SESSION[ "arr" ],explode( ",",$strings) );
var_dump( $_SESSION[ "arr" ] );
?>
  </body>
</html>