dougou7008
2018-05-24 08:48
浏览 187
已采纳

使用PHP从数组中获取逗号分隔值的简便方法

I have this variable $sid and its output is below.

$sid    =   $_POST['sid'];
// sid consists values like this.
Array
(
    [0] => 1
    [1] => 2,3
)

now I need to run a query with this sid 1, 2 and 3. To do that I am using following code:

$ex = array();
foreach ( $sid as $key => $value) {
    $ex[] = explode(',', $value);
}


foreach ($ex as $key => $value) {
    foreach ($value as $k => $v) {
        echo $v;
        // my query where sid =  $v
    }
}

Is there any better way without multiple foreach loop?

图片转代码服务由CSDN问答提供 功能建议

我有这个变量$ sid,其输出在下面。

 <  code> $ sid = $ _POST ['sid']; 
 // sid包含这样的值。
Array 
(
 [0] =&gt; 1 
 [1] =&gt; 2,3 
  )
   
 
 

现在我需要使用此sid 1,2和3运行查询。为此,我使用以下代码: \ n

  $ ex = array(); 
foreach($ sid as $ key =&gt; $ value){
 $ ex [] = explode(',',$ value); 
} \  n 
 
foreach($ ex as $ key =&gt; $ value){
 foreach($ value as $ k =&gt; $ v){
 echo $ v; 
 //我的查询其中sid = $  v 
} 
} 
   
 
 

没有多个 foreach 循环有没有更好的方法?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doufu5521 2018-05-24 08:59
    已采纳

    Try this:

    $ex = explode(',', implode(',', $sid));
    
    foreach ($ex as $v) {
        echo $v;
    }
    

    Basically, your input is an array of strings of comma-separated values, so, you can merge these strings into single string with comma as separator, and then split whole thing using single explode call.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题