0

I want to generate a nested array from a string.

The String looks like this $item = "profile:my_wallet:btn_recharge";

I want to convert it to nested array like this ["profile"]["my_wallet"]["btn_recharge"]

mmghunaim
  • 13
  • 3
  • Does the php explode() function work for you? [explode()](https://www.php.net/manual/en/function.explode.php) – Rob Moll Apr 15 '21 at 12:57
  • 1
    Yes, that is possible. Do you have some code you want help with, or are you looking for a developer to pay to write it for you? – IMSoP Apr 15 '21 at 13:00
  • 1
    Welcome to Stack Overflow! Similar [questions](https://stackoverflow.com/questions/17663204/build-array-from-string-in-php) are [asked](https://stackoverflow.com/questions/14209362/how-to-create-particular-array-from-string-in-php) in regular intervals, so please [research](https://stackoverflow.com/questions/3793448/creating-array-from-string) before asking. This is the first thing the [help center article about asking](https://stackoverflow.com/help/how-to-ask) mentions. – El_Vanja Apr 15 '21 at 13:11
  • 1
    Does this answer your question? [Build Array from String in PHP](https://stackoverflow.com/questions/17663204/build-array-from-string-in-php) – Andrew Apr 16 '21 at 14:29

1 Answers1

0

What you could use is a simple recursion to go as deep as you like.

function append(array $items, array $array = []): array
{
    $key = array_shift($items);
    if (!$key) return $array;
    $array[$key] = append($items, $array);
    return $array;
}

$array = append(explode(':', "profile:my_wallet:btn_recharge"));

The result of $array looks like below and can be accessed as you asked

$array['profile']['my_wallet']['btn_recharge'];
array (
  'profile' =>
  array (
    'my_wallet' =>
    array (
      'btn_recharge' =>
      array (
      ),
    ),
  ),
)
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35