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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?