简体   繁体   中英

How can I convert 3-D multidimentional array to 1-D array as below where I want to insert last array's values into that particular array's keys?

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.

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);
    }
}

This will do the trick:

<?php

$arr = [
    'data' => [
        28 => [201,202],
        29 => [301,302],
        30 => [401,402],
    ]
];

$return = [];
foreach ($arr['data'] as $key => $value) {
    $return[] = ['data1' => $key, 'data2' => $value];
}

var_dump($return);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM