A helper like this would be great for those using a package like Sentry, for example.
...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.
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?
Most helpful comment
Well that can easily be done :