Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
$data = array('str1', 'str2', 'str3', 'str4', 'str5');
$c=count($data)-1;
$a='';
if($c==0)
$a=array($data[0]);
else
for($i=$c;$i>=0;$i--)
{
if($i==$c)
$a=$data[$i];
else
$a=array($data[$i],'sub'=>$a);
}
function str_tree($arr, $i = 0)
{
$res = array();
if( isset($arr[$i]) ){
$res[] = $arr[$i++];
$res['sub'] = str_tree($arr, $i);
}
return $res;
}
function str_tree($arr, $i = 0)
{
return isset($arr[$i]) ? array($arr[$i++], 'sub' => str_tree($arr, $i)) : NULL;
}
After additional examples, it turns out that your original example was incorrect, since the last element is now not a string, but an array.
For this case, the code is a bit simpler
$data = array('str1', 'str2', 'str3', 'str4', 'str5');
$c=count($data)-1;
$a='';
for($i=$c;$i>=0;$i--)
{
if($i==$c)
$a=array($data[$i]);
else
$a=array($data[$i],'sub'=>$a);
}
print_r($a);
> There is an array of lines. You need to invest them in each other.
Who are they? Strings? An array of strings somewhere? Strings to an array? :) The problem is not clear.
You can approach from the end:
$data = array('str1', 'str2', 'str3', 'str4');
$result = array(end($data));
while (false !== ($i = prev($data))) {
$result = array($i, 'sub'=>$result);
}
There is an array_reduce for something like this :
$my = array_reduce(array_reverse($data), function($result, $item) {
return array($item, 'sub' => $result);
}, array());
sub
one, but if this is really necessary, then we select it specially:$my = array_reduce(array_reverse(array_slice($data, 0, -1)), function($result, $item) {
return array($item, 'sub' => $result);
}, array_slice($data, -1));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question