I have an array as given below
JavaScript
x
$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.
JavaScript
$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.
JavaScript
function nestArray($arr, $value) {
if (!count($arr)) {
return $value;
}
foreach (array_reverse($arr) as $key) {
$new = [$key => $value];
$value = $new;
}
return $new;
}
Example
JavaScript
$arr = ['Product', 'Category', 'Rule'];
$nested = nestArray($arr, 'fixed');
print_r($nested);
Output
JavaScript
Array
(
[Product] => Array
(
[Category] => Array
(
[Rule] => fixed
)
)
)