I have this array:
$input = ['a', 'b', 'c', 'd'];
the output should be:
$output = convertArrayValues($input, 'final');
$output['a']['b']['c']['d'] = 'final;
I need code for convertArrayValues() method which will do the job of converting:
$input = ['a', 'b', 'c', 'd'];
into:
$output['a']['b']['c']['d'] = 'final;
Dumped array input:
array:4 [
0 => "a"
1 => "b"
2 => "c"
3 => "d"
]
Dumped array output:
array:1 [
"a" => array:1 [
"b" => array:1 [
"c" => array:1 [
"d" => 'final
]
]
]
]
>Solution :
Will this help?
function convertArrayValues($input, $value) {
$output = [];
$temp = &$output; // reference to the output array
foreach ($input as $key) {
$temp[$key] = []; // create or set a nested array if it's the last item
$temp = &$temp[$key]; // update reference to point to the newly created array
}
$temp = $value; // final value
return $output;
}
convertArrayValues($input, 'final');