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"]

4
  • Does the php explode() function work for you? explode() Commented Apr 15, 2021 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? Commented Apr 15, 2021 at 13:00
  • 1
    Welcome to Stack Overflow! Similar questions are asked in regular intervals, so please research before asking. This is the first thing the help center article about asking mentions. Commented Apr 15, 2021 at 13:11
  • 1
    Does this answer your question? Build Array from String in PHP Commented Apr 16, 2021 at 14:29

1 Answer 1

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 (
      ),
    ),
  ),
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.