du8980919 2013-03-04 14:39
浏览 34
已采纳

使用数字键合并两个数组,以便在多行中插入MySQL中的关联数组值

I'm getting two arrays $post_img & $post_sort resulting:

 Array
(
    [0] => test1.jpg
    [1] => test2.jpg
    [2] => test3.jpg
)
Array
(
    [0] => 3
    [1] => 1
    [2] => 2
)

I'd like to merge them like:

Array
(
    [Image] => Array
        (
            [0] => test1.jpg
            [1] => test2.jpg
            [2] => test3.jpg
        )
    [Sort] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 2
        )
)

Because I think its the best way to insert them into my Database each entry in one row like:

ID | Image       | Sort 
1    test1.jpg     3
2    test2.jpg     1
3    test3.jpg     2  

The point is that I think this should be possible with only one query. I had different tries but none of them ended up good.

  • 写回答

3条回答 默认 最新

  • dqbh8054 2013-03-04 14:43
    关注

    Use array:

    $newarray = array('Image' => $post_img, 'Sort' => $post_sort);
    

    For adding the data to your table, you can go with your original arrays:

    $sql = "INSERT INTO tablename SET Image=:image, Sort=:sort";
    $dbImgInsert = $db->prepare($sql); // preparing sql for insert, using parameters
    
    $c = count($post_img)-1;
    
    for ($i=0;$i<=$c;$i++;) { // looping through the arrays
    
        $dbImgInsert->execute(array(   // inserting the data into the prepared query and into the db
            'image' => $post_img[$i],
            'sort' => $post_sort[$i]
            ));
    } // for
    

    The above example assumes you are using MySQL with PDO.

    To create a single INSERT-statement the classic way, go:

    $sql="";
    $c = count($post_img)-1;
    for ($i=0;$i<=$c;$i++;) { // looping through the arrays
    
        $sql.="('{$post_img[$i]}', '{$post_sort[$i]}'), ";
    }
    $sql ="INSERT INTO tablename (Image, Sort) VALUES " . trim($sql,',');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?