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

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

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog