php数组套数组叫是多维数组,PHP数组-如何将一维数组嵌套到多维数组中?

其思想是保留一个辅助数组,其中包含找到的所有节点(父节点和子节点)。这个数组的值是支持结果的引用。

这将以线性时间构建树(array_key_exists执行哈希表查找,平均为o(1)):

//table contains (id, parent)

$orig = array(

11 => 8,

7 => 3,

8 => 7,

99 => 8,

16 => 8,

);

$childrenTable = array();

$result = array();

foreach ($orig as $n => $p) {

//parent was not seen before, put on root

if (!array_key_exists($p, $childrenTable)) {

$childrenTable[$p] = array();

$result[$p] = &$childrenTable[$p];

}

//child was not seen before

if (!array_key_exists($n, $childrenTable)) {

$childrenTable[$n] = array();

}

//root node has a parent after all, relocate

if (array_key_exists($n, $result)) {

unset($result[$n]);

}

$childrenTable[$p][$n] = &$childrenTable[$n];

}

unset($childrenTable);

var_dump($result);

给予

array(1) {

[3]=>

array(1) {

[7]=>

array(1) {

[8]=>

array(3) {

[11]=>

array(0) {

}

[99]=>

array(0) {

}

[16]=>

array(0) {

}

}

}

}

}

编辑:未设置

$childrenTable

最后清除参考标志。实际上,您可能无论如何都希望在函数内部执行操作。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值