0

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.

1
  • $data[$user][$month][$newsubarray] = $data[$user][$month]; Something like this? Commented May 16, 2017 at 14:08

3 Answers 3

2

You can use array_map, check the live demo

if you want to pass parameter to array_map(), use this

array_map(function($v) use($para1, $para2, ...){...}, $array);

Here is the code,

<?php

$array =array('user'=> array('month'=>array('id' =>2, 'company' => 3)));
print_r($array);
print_r(array_map(function($v){
  $arr = $v['month'];
  $v['month'] = [];
  $v['month']['newsubarray'] = $arr;
  return $v;}
, $array));
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

this worked, had to exclude 2 values because they have a summary. thank you very much.
0

Your last level of array, you can create object, for holding data with implementing ArrayAccess. Then simply by reference, assign object in desire places. This way, you can hold 1 object and use it multi places, but if you change in one - this change in all.

Then you addictionaly, can implements __clone method to clone object correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.