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 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数