Reputation: 20574
I would like to change the value of a recursive array.
One array provides the path
to the variable to change:
$scopePath
represents the path to change.
For example if $scopePath==Array("owners","products","categories")
and $tag="price";
I would like to change $value["owners"]["products"]["categories"]["tag"]
to true
$u=$value;
foreach ($scopePath as $i => $s) {
if (!isset($u[$s]))
$u[$s]=Array();
$u=$u[$s];
}
$u[$tag]=true;
I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
Upvotes: 0
Views: 41
Reputation: 2769
Make $u
referencing $value
or an element inside $value
.
$u = &$value;
foreach($scopePath as $i => $s) {
if (!isset($u[$s]))
$u[$s]=Array();
$u = &$u[$s];
}
$u["tag"] = true;
When $scopePath = array("owners","products","categories")
print_r($value);
will output
Array
(
[owners] => Array
(
[products] => Array
(
[categories] => Array
(
[tag] => 1
)
)
)
)
Upvotes: 1
Reputation: 13340
To change your $value
variable you must use &
in first line:
$u = &$value;
Upvotes: 1