0

I'm writing a PHP script in which I got a multidimensional array without fixed depth. Eg:

$myArray = [ 'item01' => [ 'section01' => [ 'part01' ] ], 'item02' => [ 'section02' => [ 'part02' => [ 'something01' ] ] ], 'item03' => [ 'section03' ] ] 

I have a string that contains the path to the value that should be changed. Eg:

$myPath = 'item02/section02/part02' 

And I have the new value:

$myValue = 'somethingElse' 

What I'm trying to do, is go through array $myArray following the path set in $myPath to change the value to $myValue.

The expected output, with the examples above, would be this:

$myArray = [ 'item01' => [ 'section01' => [ 'part01' ] ], 'item02' => [ 'section02' => [ 'part02' => [ 'somethingElse' ] ] ], 'item03' => [ 'section03' ] ] 

I've tried several ways, but keep getting stumped on this. In the end, it always reaches a point where the solution is, at its core, the same. Rubber duckying didn't help either. Other programmers I know, haven't been able to find a solution either.

I'm hoping someone here can at least provide some fresh ways to look into this.

PS: Everything above is in pseudo-code, as this problem doesn't seem to be language-specific.

4
  • Not a duplicate. That one is for a multidimensional array with fixed depth. All solutions offered in that question won't work with the problem explained here. Commented Oct 6, 2017 at 13:11
  • Show your expected output Commented Oct 6, 2017 at 13:15
  • Added the expected output Commented Oct 6, 2017 at 13:20
  • 1
    @mega6382 It most certainly did! I'm a bit surprised, as I tried this before too and it didn't work then. I must've made a tiny error somewhere. I'll see what that was after wrapping this up. Thanks for the help! Commented Oct 6, 2017 at 14:03

1 Answer 1

1

try the following:

$myPath = 'item02/section02/part02'; $path = explode('/', $myPath); $arr = &$myArray; foreach($path as $key) { $arr = &$arr[$key]; } $arr = "somethingElse"; var_dump($myArray); 

First turn the $myPath string into an array of keys using explode.

This uses a simple loop foreach loop to loop over the array using keys, and then by passing the values by reference it replaces the deepest value. Demo Here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This seems to work in the demo. I've tried it in my code now, and it seems to work as well! The odd thing is, I tried this before as well, but it kept overriding the entire array. I'm curious as to what the difference is. I'll look into that after wrapping this up.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.