My question is the following:
I'm looking tor an algorithm which makes $array1
look like $pyramid
.
I Have this array:
$array1 = [
'foo',
'baz',
'bar',
'apple'
];
And I want to create a new array ($pyramid
) from $array1
which looks like this:
$pyramid = [
'foo' => [
'baz' => [
'bar' => [
'apple' => ' '
]
]
]
];
The example $array1
has 4 elements, but it can be arbitrarily long, so the algorithm should work any dimension.
You mean something like:
$pyramid = [];
$pyramidPtr = &$pyramid;
foreach ($array1 as $element) {
$pyramidPtr[$element] = null;
$pyramidPtr = &$pyramidPtr[$element];
}
unset($pyramidPtr);
var_dump($pyramid);
You can use array_walk
along with array_reverse
like as
$reversed = array_reverse($array1);
$result = [];
array_walk($reversed,function($v,$k)use(&$result){
$result = $v ? [$v => $result] : "";
});
print_r($result);