Epsilon47
Epsilon47

Reputation: 838

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.

Upvotes: 3

Views: 5944

Answers (4)

Bedram Tamang
Bedram Tamang

Reputation: 4365

Laravel has an array undot method.

use Illuminate\Support\Arr;
 
$array = [
    'user.name' => 'Kevin Malone',
    'user.occupation' => 'Accountant',
];
 
$array = Arr::undot($array);
 
// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]

Reference: https://laravel.com/docs/8.x/helpers#method-array-undot

Upvotes: 3

lagbox
lagbox

Reputation: 50481

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

Upvotes: 3

Troyer
Troyer

Reputation: 7013

No, Laravel by default only gives you array_dot() helper, which you can use to flat an multidimensional array into dot notation array.

Possible solutions

Easiest way is to use this little package that adds array_undot() helper to your Laravel, then like the package docs says, you could do something like this:

$dotNotationArray = ['products.desk.price' => 100, 
                     'products.desk.name' => 'Oak Desk',
                     'products.lamp.price' => 15,
                     'products.lamp.name' => 'Red Lamp'];

$expanded = array_undot($dotNotationArray)

/* print_r of $expanded:

[
    'products' => [
        'desk' => [
            'price' => 100,
            'name' => 'Oak Desk'
        ],
        'lamp' => [
            'price' => 15,
            'name' => 'Red Lamp'
        ]
    ]
]
*/

Another posible solution is to create a helper function with this code:

function array_undot($dottedArray) {
  $array = array();
  foreach ($dottedArray as $key => $value) {
    array_set($array, $key, $value);
  }
  return $array;
}

Upvotes: 3

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40899

Laravel doesn't offer a function like that.

Upvotes: -1

Related Questions