How to extend the dot matrix into a full multidimensional array

In my Laravel project, I have a point notation block that I need to convert to a multidimensional array.

The array looks 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?

+4
source share
1 answer

You can use array_set()for this:

The array_set function sets the value inside a deeply nested array using "point" notation:

Attempt:

    $multiDimensionalArray = [];

    foreach ($dotNotationArray as $key => $value) {
        array_set($multiDimensionalArray , $key, $value);
    }

    dump($multiDimensionalArray);

Explanation:

array_set()sets the value for the key in dot notation format to the specified key and displays an array of type ['products' => ['desk' => ['price' => 200]]]. so you can loop through the keys of an array to get a multidimensional array.

+5

Source: https://habr.com/ru/post/1693504/


All Articles