-1

I have a given path with keys (in a separate array) to a subarray within a multidimensional one.

$path_array = array( 'first', 'new', 'best');
$multi_data = array(
  'first' => array(
    'example' => 'good',
    'other' => 'well',
    'new' => array(
      'subset' => 'none',
      'best' => 'stackoverflow',
    )
   )
);

The arrays are changing of course due to dynamically generated data.

My Question: How to get the correct value or array by the path that i have got? A correct static approach would be:

echo $multi_data['first']['new']['best'];
// prints: stackoverflow

I tried foreach-Loop on $path_array, but i cant put the path elements together (keys is square brackets).

3
  • Will there be duplicates on any key? if so then what's the case there. Also are you just look to return the particular path array from $multi_data? Is $path_array constant or will be changing as well? And is the order in $path_array the order you need to search? Commented Nov 13, 2023 at 17:10
  • The values in $path_array stand for every indentation level. On each indentation every key is unique. But duplicates on different indentations can occur. $path_array will change, too because its generated dynamically. Commented Nov 13, 2023 at 17:36
  • So the size of $path_array is also n and not fixed right? Just a thought, having a path in an array might not be the most efficient way, you should use a linked list. Commented Nov 13, 2023 at 17:48

1 Answer 1

-1

EDIT: don't know why I went through all this trouble with shifting values, foreach works just fine

Could do something like:

$result = $multi_data;
foreach($path_array as $key){
    $result = $result[$key];
}
echo $result;

The idea is to get deeper into the array with each iteration. Be extra careful if you might have some non-existent keys, though.

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

3 Comments

Just realized i used this way to read the element. How about writing directly to it: $a['first']['new']['best'] = 'stackexchange';
@Arthur Please remove your advice from this page and transfer it to the the canonical (or at least an earlier asked question)
@stephan the canonical demonstrate reading and writing using key paths.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.