我有那个阵列:
$a = array(
"7" => array(
"id" => 7,
"parent" => 6
),
"6" => array(
"id" => 6,
"parent" => 5
),
"5" => array(
"id" => 5,
"parent" => 4
),
"4" => array(
"id" => 4,
"parent" => 0
),
"3" => array(
"id" => 7,
"parent" => 2
),
"2" => array(
"id" => 7,
"parent" => 1
),
"1" => array(
"id" => 7,
"parent" => 0
)
);
我想要的结果是:
$a = array(
"4" => array(
"id" => 4,
"parent" => 0,
array(
"5" => array(
"id" => 5,
"parent" => 4,
array(
"6" => array(
"id" => 6,
"parent" => 5,
array(
"7" => array(
"id" => 7,
"parent" => 6
)
)
)
)
)
)
),
"2" => array(
"id" => 7,
"parent" => 1,
array(
"3" => array(
"id" => 7,
"parent" => 2
)
)
),
"1" => array(
"id" => 7,
"parent" => 0
)
);
我使用的代码是:
foreach($a as $v)
{
if(isset($a[$v['PARENT']]))
{
$a[$v['PARENT']][$v['ID']] = $v;
unset($a[$v['ID']]);
}
}
我遇到的问题是我得到了那个结果:
$a = array(
"4" => array(
"id" => 4,
"parent" => 0,
array(
"5" => array(
"id" => 5,
"parent" => 4
)
)
),
"2" => array(
"id" => 7,
"parent" => 1,
array(
"3" => array(
"id" => 7,
"parent" => 2
)
)
),
"1" => array(
"id" => 7,
"parent" => 0
)
);
而不是需要它。
答案 0 :(得分:4)
要解决您的问题,您需要正确理解variable referencing/aliasing in PHP的工作原理。
请看下面的示例代码,它与您的代码没什么不同,但是使用引用来访问任何父代,即使它已经“移动”了:
# transform $flat into a tree:
foreach($flat as $id => &$value)
{
# check if there is a parent
if ($parentId = $value['parent'])
{
$flat[$parentId][0][$id] =& $value; # add child to parent
unset($flat[$id]); # remove reference from topmost level
}
}
unset($value); # remove iterator reference
print_r($flat); # your tree
$flat
现在包含$flat
的所有值 - 但重新排序。 Demo
答案 1 :(得分:1)
您确定输出数组是否正确?当然,密钥2
应该是1
的孩子(因为2
有'parent'=>1
)?如果不是这种情况,我不明白实际上要做什么以及密钥如何相互关联。
如果2
应该是1
的孩子,则可行:
$keep = array();
foreach ($a as $k => &$v) {
// Loop the array first time and create references to
// structure the array how you want it
if ($v['parent']) {
$a[$v['parent']][0] = array($k => &$v);
} else $keep[] = $k;
}
foreach ($a as $k => $v) {
// Loop it again to get rid of non-root nodes from the root
if (!in_array($k,$keep)) {
unset($a[$k]);
}
}
print_r($a);