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条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法