我在构建分层数组结构时遇到了一些问题——我几乎已经完成了,但是有一些无法解释的东西让我的数组看起来很奇怪,我希望你能帮助我。
树形结构为:
root
|data
|-children
|--data
|--children
|---data
|---children
任何孩子都可以有任意数量的孩子,每个孩子可以有任意数量的父母。
我有一个构建树的函数:
private function build_tree($rows,$parent) {
$i = 0;
$response -> result = array();
$result = array();
$leaf = false;
foreach($rows as $row) {
if($row['parent_id'] == $parent) {
$leaf = is_null($row['treeDef']) ? false : true;
$workingSet = array_merge($result,array(
'id' => (int)$i,
'parent_id' => (int)$row['parent_id'],
'child_id' => (int)$row['id'],
'name' => (string)$row['resourceName'],
'updated' => strtotime($row['updated']),
'purchasedUnit' => (string)$row['purchasingUnit'],
'purchasedCost' => (double)$row['purchasingCosts'],
'purchasedDiscount' => (double)$row['discount'],
'estimateUnit' => (string)$row['estimatingUnit'],
'profitAddOn' => (string)$row['profitAddOn'],
'landedCost' => (double)$row['landedCost'],
'unitCorrelation' => (double)$row['unitCorrelation'],
'leadTime' => (string)$row['leadTime'],
'ResourceClassShortname' => (string)$row['ResourceClassShortname'],
'supplierName' => (string)$row['nameSupplier'],
'iconCls' => (string)$row['typeIcon'],
'leaf' => $leaf
));
$hasChildren = $this->Resource_model->has_children($rows,$row['id']);
if ($hasChildren->check) {
if (!$leaf) {
for($j=0; $j <= ($hasChildren -> rows); $j++) {
$parentArray = $workingSet;
$childArray = $this -> Resource_model -> build_tree($rows,$row['id']);
$workingSet = array_merge($parentArray,array('children' => $childArray -> result));
}
}
}
$result[$i] = $workingSet;
$i++;
}
}
$response -> result = $result;
$response -> rows = $i;
return $response;
}
这会产生这个 JSON:
每个有 2 个孩子(或更多? - 没有测试值)的项目都会像应该的那样获得第一个项目,但第二个项目也包含第一个项目 - 复制所有结果。
任何帮助表示赞赏。