doukezi4606 2019-03-11 19:58
浏览 76
已采纳

嵌套foreach,如何更高效

First of all, hello I'm currently making a report system who does take 6 fields(6 selects, all of them being multiples).

I receive their input as a array, and i need process each value for each field

For example, let's give the fields A, B and C.

The field A have the values [1, 2, 3].

The field B have the values [4,5,6].

The field C have the values [7,8,9].

I need make the code run and return like this

1-4-7
1-4-8
1-4-9
1-5-7
1-5-8
1-5-9
( And so on )

Actually, i'm doing this by nesting several foreach's, but i believe it is inefficient(i'm taking almost 30 to 35 seconds to do the loop(without consider the MySQL Query i do inside it)

Does exists a more efficient way to do this?

EDIT

As requested on the comments, i got a example

// I'm ignoring SQL Injection since it is a example only
$status = explode("-", $_POST['status']);
$type = explode("-", $_POST['type']);
$store = explode("-", $_POST['store']);

foreach($status as $statusKey => $statusID) {
    foreach($type as $typeKey => $typeID) {
        foreach($store as $storeKey => $storeID) {
            echo $statusID." - ".$typeID." - ".$storeID.PHP_EOL;
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dongzhang0418 2019-03-11 20:27
    关注

    What you need to do is to prepare a statement in the loops and execute it outside of the loops, so you will have something like this:

    INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
    

    More here: https://dev.mysql.com/doc/refman/8.0/en/insert.html

    Without INSERT this code should be super fast as this are very basic operations.

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

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献