edi9999
edi9999

Reputation: 20574

Change inner value of recursive array

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

Answers (2)

netiul
netiul

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

Michael Sivolobov
Michael Sivolobov

Reputation: 13340

To change your $value variable you must use & in first line:

$u = &$value;

Upvotes: 1

Related Questions