php 递归数组添加,在PHP中创建递归数组

我正在尝试基于字符串的长度创建递归数组:字符串长度是节点的级别.这实际上是在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);

标签:php,arrays,recursion,yii

来源: https://codeday.me/bug/20190830/1768223.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值