【发布时间】:2012-02-25 09:19:52
【问题描述】:
为了能够搜索和索引/排序数组
我有一个要解析的大型多维数组。现在,我只是使用 CakePHP shell 来做这件事,但任何方法都足够了。我需要做的是获取父/子/更多子的数组并创建一个带有关联的“大纲编号”的 id 数组
例如:
1
1.1
1.2
1.2.1
1.2.2
1.2.3
等等。
这是我的“输入数组”的示例:
Array
(
[0] => Array
(
[AsapStructure] => Array
(
[id] => 1
[lft] => 30267
[rght] => 32774
[parent_id] =>
[wbs] =>
)
[children] => Array
(
[0] => Array
(
[AsapStructure] => Array
(
[id] => 2
[lft] => 30268
[rght] => 30773
[parent_id] => 1
[wbs] => 1
)
[children] => Array
(
[0] => Array
(
[AsapStructure] => Array
(
[id] => 3
[lft] => 30269
[rght] => 30382
[parent_id] => 2
[wbs] => 1.1
)
我的设想是拥有一个简单的自递归解析机制。我开发的一个例子如下:
<?php
var $structIndex = array();
private function __parseStruct( $toParse,$prefix = null ) {
$iterator = 0;
if ( $prefix )
$prefix = $prefix . '.';
foreach( $toParse as $datum ) {
$iterator++;
if ( $datum['AsapStructure']['id'] == 1 )
$this->structIndex[ 1 ] = NULL;
else
$this->structIndex[ $datum['AsapStructure']['id'] ] = $prefix . $iterator ;
$subiterator = 0;
foreach( $datum['children'] as $key => $data ) {
$subiterator++;
$this->structIndex[ $data['AsapStructure']['id'] ] = $prefix . $subiterator;
if ( ! empty( $datum['children'] ) ) {
$this->__parseStruct( $datum['children'], $subiterator );
}
}
}
return $this->structIndex;
}
?>
我要做的是调用这个$this->__parseStruct( $data ) 函数并将数组传递给它。然后该函数在数组上循环,为嵌套的子数组调用该函数。我的那部分工作正常,我似乎无法正确创建“索引”的逻辑,即 1.1、1.2、1.2.1 等等。
所以我的目标输出是:
$array[ $rowid ] = [ 1.1 / 1.2 / 1.2.1 / 1.2.2 ] or any combination as such.
非常感谢任何帮助。
【问题讨论】:
标签: php arrays cakephp multidimensional-array tree