1

I have an array like this:

[0] => [basketball][player]
[1] => [basketball][threes][player]
[2] => [basketball][home][leaders][player]
[3] => [basketball][away][leaders][player]

I want to translate each element into a reference to a certain element in an associative array:

$post['basketball']['player']
$post['basketball']['threes']['player']
etc.

Is there any way to automatically translate the former into the latter? It would be super convenient if so, and presumably super inconvenient if not, so I hope there's a way, but I don't know what it might be.

1 Answer 1

2

I would say something like this:

  • Strip off the [ at the start and the ] at the end (using substr)
  • Use explode to split the string by ][
  • Loop through the exploded pieces, using them as keys to the array.

So something like this:

$array = ..... // the big array
$str = "[basketball][player]";
$keys = explode("][",substr($str,1,-1));
$pos = $array; // PHP does a lazy copy, so there is no performance issue here
while($key = array_shift($keys)) $pos = $pos[$key];
// $pos is now your target element
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. Unfortunately it doesn't seem to work. I believe this would try to get $pos['basketball'] and $pos['player'] separately, when what I want is $pos['basketball']['player']. (This conclusion is based on copying and pasting this code into my app and trying it.)
You are correct, it gets $pos['basketball'] followed by $pos['player'], but it assigns back to $pos so the result is $pos['basketball']['player'].

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.