dpy83214 2017-09-19 12:26
浏览 20

消除PHP循环

I have a post array and need to create a new array format from this to store in database with batch insert. I have achieved it with the following code. But want a better solution (if any) to achieve my array. I wanted to eliminate the inner loop but did not get any solution. Please provide any suggestion on how can I achieve this.

Code to parse array:

if ($this->input->post()) {
    foreach ($this->input->post() as $key => $value) {
        $i = 0;

        /* need to eliminate this loop */
        foreach ($value as $k => $v) {
            $postData[$i][$key] = $v;
            $i++;
        }
    }
}

Input array:

Array
(
    [category_id] => Array
        (
            [0] => 1
            [1] => 4
        )

    [pay_type_id] => Array
        (
            [0] => 2
            [1] => 5
        )

    [frequency_id] => Array
        (
            [0] => 3
            [1] => 6
        )

)

Output array;

Array
    (
        [0] => Array
            (
                [category_id] => 1
                [pay_type_id] => 2
                [frequency_id] => 3
            )

        [1] => Array
            (
                [category_id] => 4
                [pay_type_id] => 5
                [frequency_id] => 6
            )

    )
  • 写回答

4条回答 默认 最新

  • dragonfly9527 2017-09-19 12:35
    关注

    Because you have two arrays, a:"records" and b:"fields" in any case, theoretically, you need to have at least two loops to populate the "records" and "fields" inside a record. And, basically, this is not a bad approach or a problem.

    If you really want just one loop, because of faith reasons, you need to put a hard-coded list of field assignments in first loop that populate the records.

    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题