4

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?

1

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.