我有这个数组
Array
(
[0] => dev3
Array (
[0] => ->content
Array (
[0] => ->->mktg
Array(
[0] => ->->->pls1
[1] => ->->->pls2
[2] => ->->->config
)
[1] => ->->splash
)
)
)
我想将此字符串转换为多维数组。像这样
{{1}}
任何人都可以这样做吗
答案 0 :(得分:3)
如果等级在任何步骤
上增加+1以上,它就不起作用$str = 'dev3->content->->mktg->->->pls1->->->pls2->->->config->->splash';
$in = preg_split('/(?<!>)(?=->)/', $str);
上面我们从输入字符串
创建这样的数组Array
(
[0] => dev3
[1] => ->content
[2] => ->->mktg
[3] => ->->->pls1
[4] => ->->->pls2
[5] => ->->->config
[6] => ->->splash
)
继续工作
$result = [];
$p = &$result;
$level = 0;
foreach($in as $i) {
// Count next level
$c = substr_count($i, '->');
// if level is not changed
if($c == $level) { $p[] = $i; continue; }
// level increased
if ($c == $level + 1) {
$level++;
$p[] = [$i];
$p = &$p[count($p)-1];
continue;
}
// any level less then achived before
if ($c < $level) {
$p = &$result;
$level = $c;
while($c--)
$p = &$p[count($p)-1];
$p[] = $i;
continue;
}
die("I can't process this input string");
}
print_r($result);