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

SOURCE: http://stackoverflow.com/questions/6123061/php-set-the-value-of-a-multidimensional-associative-array-element-using-a-path

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

$array[‘a’][‘b’][0][‘c’];
$array[‘a’][‘b’][1][‘c’];
$array[‘a’][‘d’][0][‘c’][‘c’];
$array[‘b’][‘c’];
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:

$array[‘a’][‘b’][0][‘c’]=’value0-0′;
$array[‘a’][‘b’][1][‘c’]=’value0-1′;
$array[‘a’][‘d’][0][‘c’][‘c’]=’value1-0′;
$array[‘b’][‘c’]=’value2-0′;
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?

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

Advertisements
This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s