Convert multidimensional array to nested objects php

I want to convert an multidimensional array into nested objects. Here is an example of my array but this array can be of any index length. My solution works for only given index length of the array in the example

$associativeArray = [
    'key' => [
        [
            'name' => 'hey',
            'value' => 'hello',
        ],
        [
            'name' => 'hey1',
            'value' => 'hello1',
        ],
        [
            'name' => 'hey2',
            'value' => 'hello2',
        ],


    ],
    'test' => [
        [
            'name' => 'hey3',
            'value' => 'hello3',
        ]
    ]
];

I achieved this way for my need but not very elegant

foreach ($associativeArray as $subArray) {
    foreach ($subArray as $key => $value) {
        $subArray[$key] = (object)$value;
    }
    $nestedObjects[] = (object)$subArray;
}

$nestedObjects = (object)$nestedObjects;

I wanna be able to convert the multidimensional of any dimensions to nested objects. can someone suggest a elegant way please?


A quick way to do this is:

json_decode(json_encode($associativeArray));

json_encode($associativeArray) will convert array to json string

json_decode will convert json string to stdClass object.