dqyat62284 2014-07-04 04:30
浏览 72
已采纳

PHP拆分逗号分隔字符串然后为拆分数组中的每个值添加相同的值? [关闭]

What the code in PHP to do that:

$string = '123,456,789,102'  
$value = '564'

How to split $string into an array then concatenated each value in the array with $value into two dimensional array, so the final result:

$result = (   
    (564,123),  
    (564, 456),  
    (564, 789),  
    (564, 102)              
)  

So $result can be used in inserting multiple rows in mysql using PDO:

  $stmt = $this->pdo->prepare('INSERT INTO tbl_user (id, bought) VALUES ((?,?),

       (?,?),
       (?,?),
       (?,?),
       (?,?),

            )');

       $stmt->execute($result);

note: id and bought columns are varchar

  • 写回答

4条回答 默认 最新

  • douyou2048 2014-07-04 04:41
    关注

    // exploding & storing $string into an array. Array contains $string as strings.

     $s_array = explode(",", $string);
    
    //to remove spaces
    
    $spaces=array(); //to store space
    $others=array(); //to store characters
    foreach($s_array as $word)
    {
        if($word=='')
        {
            array_push($spaces,$word); //spaces are stored into space array
        }
        else
        {
            array_push($others,$word);  //string variables are stored into others array
        }
    }
    
    $count=count($others);
    

    Now use a for loop.

    for($i=0;$i<$count;$i++)
    {
    for($j=0;$j<$count;$j++)
    {
    $result[$i][$j] = $value;
    $result[$i][$j+1] = $others[$i];
    }
    }
    

    If you want to convert the string array into integers.... do something like this...

    $integerarray = array_map('intval', array_filter($others, 'is_numeric'));
    foreach($integerarray as $var) 
     {
    array_push($result, array($value, $var) );
    }
    

    and do the coding.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler