Framework: Opposite of helper array_dot()

Created on 11 Jul 2013  路  11Comments  路  Source: laravel/framework

A helper like this would be great for those using a package like Sentry, for example.

Most helpful comment

Well that can easily be done :

$array = array();
foreach ($arrayDot as $key => $value) {
  array_set($array, $key, $value);
}

All 11 comments

...what is the opposite of array_dot exactly ?

The array_dot function flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth.

The opposite would take a single level array that uses the "dot" notation to indicate depth, and expand it to the multi-dimensional array.

For example:

$array = array('foo.bar' => 'baz');
$array = array_dot($array);
// array('foo' => array('bar' => 'baz'));

Well that can easily be done :

$array = array();
foreach ($arrayDot as $key => $value) {
  array_set($array, $key, $value);
}

Oh, cool! I didn't notice that array_set() looked at dot syntax. Thanks so much!

Where can write that as my own helper function for quick and easy access?

You can always put that in start/global.php or create a separate app/helpers.php file that you include at the end of global.

Perfect - thanks again.

$user = $this->socialite->driver('google')->user();
$user= array_dot($user); // flatten a multi-dimensional array into a single level.
dd($user['avatar']); // ex : return the value of avatar(image link)

I've put a solution to this into a very small composer package, as we were finding it useful in several projects. It provides an array_undot helper function that expands a dot notation array into a multi-dimensional array.

https://github.com/divineomega/array_undot

The array_set function sets a value within a deeply nested array using "dot" notation

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


        foreach ($array_dot as $key => $value) {
            array_set($array, $key, $value);
        }

Result

{
"products": {
"desk": {
"price": 100,
"name": "Oak Desk"
},
"lamp": {
"price": 15,
"name": "Red Lamp"
}
}
}

Any idea why is this not in Laravel official Array helper?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JamborJan picture JamborJan  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

SachinAgarwal1337 picture SachinAgarwal1337  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments