I would like to take an array, say:
array("one", "two", "three");
and make it into an array of arrays, like:
$someArray["one"]["two"]["three"];
The array of arrays ($someArray
) would have to be created by some sort of loop as the initial array is created by an explode()
so i don't know how deep $someArray
would be.
I hope this is clear, thanks all for your time!
I am reading up on it at the moment myself, would array_map()
work for this?
You should use array_reduce. The solution is quite simple.
To do the trick, reverse the array and only then apply the reduction.
$a = array('a','b','c');
$x = array_reduce(array_reverse($a), function ($r, $c) {
return array($c=>$r);
},array());
EDIT an expanded and explained version:
In php we don't have a function to go deep into an array automatically but we haven't to. If you start from the bottom, we will be able to enclose an array into the previous one with a simple assignation.
$a = array('a','b','c');
$result=array(); // initially the accumulator is empty
$result = array_reduce(
array_reverse($a),
function ($partialResult, $currentElement) {
/* enclose the partially computed result into a key of a new array */
$partialResult = array($currentElement=>$partialResult);
return $partialResult;
},
$result
);
By the way I prefer the shorter form. I think it is a functional idiom and doesn't need further explanation to a middle experienced developer (with a bit of functional background). The second one add a lot of noise that, it is suitable to learn but source of distraction into production code (obviously I'm referring to function with just a return statement).