0

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.

3
  • Your code actually looks fine. What isn't working as intended? Commented Jun 11, 2013 at 10:17
  • line $u=$u[$s]; makes that the value will change the reference of $u. The $value variable doesn't change. Commented Jun 11, 2013 at 10:19
  • I think you're looking for this. Commented Jun 11, 2013 at 10:22

2 Answers 2

1

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
                        )
                )
        )
)
Sign up to request clarification or add additional context in comments.

Comments

1

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

$u = &$value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.