我正在尝试基于字符串的长度创建递归数组:字符串长度是节点的级别.这实际上是在Yii框架上构建一个树视图.这是一个例子……
Array
(
[0] => A
[1] => C
[2] => CC
[3] => CCC
[4] => P
[5] => PP
[6] => PPP
[7] => PPPE
[8] => PS
[9] => PSA
)
我想这样排序:
Array
(
[0] => Array
(
[text] => A
)
[1] => Array
(
[text] => C
[children] => Array
(
[0] => Array
(
[text] => CC
[children] => Array
(
[0] => Array
(
[text] => CCC
)
)
)
)
)
[2] => Array
(
[text] => P
[children] => Array
(
[0] => Array
(
[text] => PP
[children] => Array
(
[0] => Array
(
[text] => PPP
[children] => Array
(
[0] => Array
(
[text] => PPPE
)
)
)
)
)
[1] => Array
(
[text] => PS
[children] => Array
(
[0] => Array
(
[text] => PSA
)
)
)
)
)
)
我知道我要找出具有递归函数的东西,但我只是不知道该怎么做,尽管事实上我已经尝试了几天……有人这样做了吗?非常感谢…
解决方法:
这应该给你你想要的:
function &createNodeFromText(&$tree, $text)
{
if(strlen($text) > 1) {
//Make sure we have created the parent node(s) we need:
$parent = &createNodeFromText($tree, substr($text, 0, -1));
//Create a new tree level for the current node if needed:
if(!isset($parent["children"])) {
$parent["children"] = array();
}
$currentLevel = &$parent["children"];
}
else {
//New root node:
$currentLevel = &$tree;
}
//Look for the requested node..
$nodeText = $text;
$currentNode = null;
for ($i = 0; $i < count($currentLevel); ++$i) {
$node = &$currentLevel[$i];
if($node["text"] === $nodeText)
{
$currentNode = &$node;
break;
}
}
//..and create a new one only if we have to:
if($currentNode === null) {
$currentNode = array("text" => $nodeText);
$currentLevel[] = &$currentNode;
}
return $currentNode;
}
$source = array("A", "C", "CC", "CCC", "P", "PP", "PPP", "PPPE", "PS", "PSA");
$final = array();
foreach($source as $s) {
createNodeFromText($final, $s);
}
print_r($final);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。