Reputation: 131
In my Laravel project, I have a dot notation array which I need to convert to a multi-dimensional array.
The array is something like this:
$dotNotationArray = ['cart.item1.id' => 15421a4,
'cart.item1.price' => '145',
'cart.item2.id' => 14521a1,
'cart.item2.price' => '1245'];
How can I expand it to an array like:
'cart' => [
'item1' => [
'id' => '15421a4',
'price' => 145
],
'item2' => [
'id' => '14521a1',
'price' => 1245,
]
]
How can I do this?
Upvotes: 4
Views: 2195
Reputation: 11636
In Laravel 6+ you can use Arr::set()
for this:
The Arr::set method sets a value within a deeply nested array using "dot" notation:
use Illuminate\Support\Arr;
$multiDimensionalArray = [];
foreach ($dotNotationArray as $key => $value) {
Arr::set($multiDimensionalArray , $key, $value);
}
dump($multiDimensionalArray);
If you are using Laravel 5.x you can use the array_set()
instead, which is functionally identical.
Explanation:
Arr::set()
sets value for a key in dot notation format to a specified key and outputs an array like ['products' => ['desk' => ['price' => 200]]]
. so you can loop over your array keys to get a multidimensional array.
Upvotes: 8