Skip to content
Advertisement

Build dynamic associative array from simple array in php

I have an array as given below

$arr = ['Product', 'Category', 'Rule'];

This can be a dynamic array meaning it can sometimes have between 1-5 elements inside it and its value can change. How can we create an array as given below from the above one in a dynamic manner.

$json['Product']['Category']['Rule'] = 'fixed';

Simply put am just trying to make a multidimensional array from the values I get from the $arr.

Advertisement

Answer

This function should do it.

function nestArray($arr, $value) {
    if (!count($arr)) {
        return $value;
    }
    foreach (array_reverse($arr) as $key) {
        $new = [$key => $value];
        $value = $new;
    }
    return $new;
}

Example

$arr = ['Product', 'Category', 'Rule'];
$nested = nestArray($arr, 'fixed');
print_r($nested);

Output

Array
(
    [Product] => Array
        (
            [Category] => Array
                (
                    [Rule] => fixed
                )

        )

)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement