Jason Swett
Jason Swett

Reputation: 45134

Translate string into reference to associative array index in PHP

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.

Upvotes: 1

Views: 104

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

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

Upvotes: 2

Related Questions