PHP: Set the value of a multidimensional associative array element using a path defined in a separate array


Ok so I have an array that holds the following elements:

Then in a separate array, I have defined the path to these values:

$structure[0] = array(‘a’,’b’,’#’,’c’);
$structure[1] = array(‘a’,’d’,’#’,’c’,’c’);
$structure[2] = array(‘b’,’c’);
Finally, I have an array holding the values:

$values[0] = array(‘value0-0′,’value0-1’);
$values[1] = array(‘value1-0’);
$values[2] = array(‘value2-0’);
I’m trying to find a simple function/loop that will be able to apply the values in $values to the array path of $array that is defined in $structure.

The end result would be:

In the case of $values[0] or $values[1], it would be able to loop through each value and substitute the $structure element matching ‘#’ with the iteration number for that particular $value.

Is this simply a case of knuckling down and writing a drawn out recursive function, or is there a smart construct or php function that could provide a more elegant solution?


Thanks to Mario, my eventual solution is:

foreach ($struct as $i=>$keys)
foreach ($values[$i] as $val) {
$r = & $array;

foreach ($keys as $key) {

if ($key == “#”) { $key = $i; }

$r = & $r[$key]; // move pointer to subarray

$r = $val;

This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s