Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform dot array to associative array

In laravel, is there any function which with I could transform a string divided with dots into associative array ?

For example:

user.profile.settings into ['user' => ['profile' => 'settings']] ?

I found the method array_dot, but it works the reversed way.

like image 654
Epsilon47 Avatar asked Feb 17 '26 19:02

Epsilon47


1 Answers

The reverse of array_dot isn't exactly what you are asking for as it still needs an associative array and returns an associative array and you have only a string.

You could make this pretty easily though I suppose.

function yourThing($string)
{
    $pieces = explode('.', $string);
    $value = array_pop($pieces);
    array_set($array, implode('.', $pieces), $value);
    return $array;
}

This assumes you are passing a string with at least one dot (at least a key [before the last dot] and a value [after the last dot]). You could expand this out to be used with an array of strings and add the proper checking easily.

>>> yourThing('user.profile.settings')
=> [
     "user" => [
       "profile" => "settings",
     ],
   ]
like image 158
lagbox Avatar answered Feb 20 '26 13:02

lagbox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!