doukezi4606 2019-03-11 11: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 12: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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部