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

使用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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doufu5521
    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.

    点赞 评论

相关推荐