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.

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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)