Is there an elegant way to turn an array into multi-dimensional keys and add in a value ?
$value = "You found the giant!"
$keys = array("fee", "fi", "fo", "fum");
$output[ flipster( $keys ) ] = $value;
// $output['fee']['fi']['fo']['fum'] = "You found the giant!";
I wrote this function, which works & does what I need it to do, but I don't think it's the best solution...
function flipster( $array, $value ) {
$out = array();
$key = $array[0];
array_shift( $array );
if( count( $array ) > 0 ) {
$out[ $key ] = flipster( $array, $value );
} else {
$out[ $key ] = $value;
}
return $out;
}
In the end, I'm getting my "fee" and "fi" from a loop, so in the loop I'm doing something like this to create a new array:
$out = array_merge_recursive($out, flipster( $keys, $value ) );
Try this on for size. Can combine multiple flips into the same
array()
. Makes it easy for you to build deep array trees. It uses a reference for deep array building, not a recursive function.How about this using recursiveness: