Devon Bessemer
Devon Bessemer

Reputation: 35337

Adding to a multidimensional array from another array

I'm trying to figure out how I would do this, basically I want the function to add to the following array:

$this->array['key1']['key2']['key3'] = 'value'

From a single dimensional array like $this->keys:

Array
(
    [0] => key1
    [1] => key2
    [2] => key3
)

My function would be:

function addToArray($value) {
 $this->array = ...
}

I have had a few ideas of using foreach $this->keys or for but I don't know how I would preserve the existing array while adding new values onto it.

$keys is maintained in a separate function

For example:

foreach ($this->keys as $key) {
  $array = $this->array[$key]
}
$array = $value;

But this would create a new single dimensional array and not add to the multidimensional $this->array. Maybe I am just not thinking correctly.

Upvotes: 1

Views: 55

Answers (1)

Grexis
Grexis

Reputation: 1512

Try something like the following:

function addToArray($value){
    $tempArray = &$this->array;
    foreach($this->keys as $key){
        $tempArray = &$tempArray[$key];
    }
    $tempArray = $value;
}

Upvotes: 2

Related Questions