duanou9758 2018-10-25 17:55
浏览 28
已采纳

如何将3D多维数组转换为1-D数组,如下所示,我想将最后一个数组值插入到特定数组的键中?

My Array is as below.

Array
(
    [data] => Array
        (
            [28] => Array
                (
                    [0] => 201
                    [1] => 202
                )
            [29] => Array
                (
                    [0] => 301
                    [1] => 302
                )
            [30] => Array
                (
                    [0] => 401
                    [1] => 402
                )
        )
)

I want to convert this array as below.

myarray = Array
    (
        [0] => Array
            (
                [data1] => 28
                [data2] => Array
                    (
                        [0] => 201
                        [1] => 202
                    )
            )
        [1] => Array
            (
                [data1] => 29
                [data2] => Array
                    (
                        [0] => 301
                        [1] => 302
                    )
            )
        [2] => Array
            (
                [data1] => 30
                [data2] => Array
                    (
                        [0] => 401
                        [1] => 402
                    )
            )
    )

After converting the array as above, I am about to insert data1 and data2 values into database. Where I will loop like

for($i=0;$i<count($myarray);$i++)
{
  $year = $myarray[$i]['data1'];
  for($j=0;$j<count($myarray[$i][data2]);$j++)
  {
    insert($year,$myarray[$i][data2][$j]);
  }
}

How can I do this? Please help me. Is this proper method in for loop where insert data into nested for loop. If our data array in too big like 10000 array counts for ($i) and 1000 counts for ($j), will it create problem for the insert function?

Any other proper conversion of array is also good for me. I just want to insert values like 201,202 with 28 and 301,302 with 29 into database.

Thank you.

  • 写回答

2条回答 默认 最新

  • du656637962 2018-10-25 18:08
    关注

    Do you really need to have the intermediate array to then just insert the data?

    It would be easier to follow the idea of using a foreach() to directly insert the data from the original array...

    $myarray = [ "data" => [ 28 =>[201,202], 29 => [301,302]]];
    
    foreach ( $myarray["data"] as $year => $data )  {
        foreach ( $data as $value2 ){
            insert($year,$value2);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置