Search code examples
phparraysmultidimensional-arrayclone

clone array and add a subarray


i have the following problem. i have a large array structure which i assign values from a sql statement:

$data[$user][$month]['id'] = $data->id;
$data[$user][$month]['company'] = $data->company;
...
...

and around 30 other values.

i need to clone this array ($data) and add a subarray like:

$data[$user][$month][$newsubarray]['id'] = $data->id;
$data[$user][$month][$newsubarray]['company'] = $data->company;
...
...

i need to clone it because the original array is used by many templates to display data.

is there a way to clone the array and add the subarray without assign all the values to the cloned array? this blows up my code and is very newbi, but works.


Solution

  • You can iterate through the array with nested foreach loops.

    It would look similar to this:

    foreach ($data as $user=>$arr2) {
        foreach ($arr2 as $month=>$arr3) {
            foreach ($arr3 as $key=>$value) {
                $data[$user][$month][$newsubarray][$key] = $value;
            }
        }
    }