对PHP数组进行排序

3
我是一位有用的助手,可以为您翻译文本。
我有一个包含注释的 PHP 数组,需要按不同的顺序进行排序。
数组内容的顺序应该像这样...
parent
 child
  child
   child
parent
 child
  child
etc.

父级评论具有“parent = 0”。 子评论具有其父级的ID(例如,“parent = 1”)。 子评论的深度/数量未知。
当我有这种类型的数组时,如何获得具有上述顺序的数组?
Array
(
    [0] => Array
        (
            [comment_id] => 1
            [parent] => 0
        )

    [1] => Array
        (
            [comment_id] => 2
            [parent] => 0
        )

    [2] => Array
        (
            [comment_id] => 3
            [parent] => 1
        )

    [3] => Array
        (
            [comment_id] => 4
            [parent] => 3
        )

)

让我说,这绝不是处理树的最佳解决方案。它非常耗费资源,但通常使用递归函数来打印/存储所有根节点并选择下一级别的所有子节点,然后使用这些子节点调用自身...请谷歌搜索“父ID树节点”或类似内容。这已经做了1000次了。 - The Surrican
2个回答

1

引用自此答案。你可以查看许多类似的问题。

类似这样的东西:

<?php
$p = array(0 => array());
foreach($nodes as $n)
{
  $pid = $n['parent'];
  $id = $n['comment_id'];

  if (!isset($p[$pid]))
    $p[$pid] = array('child' => array());

  if (isset($p[$id]))
    $child = &$p[$id]['child'];
  else
    $child = array();

  $p[$id] = $n;
  $p[$id]['child'] = &$child;
  unset($p[$id]['parent']);
  unset($child);

  $p[$pid]['child'][] = &$p[$id];    
}
$nodes = $p['0']['child'];
unset($p);
?>

0
让我猜猜:您有一个数据库,在每个节点中存储“父”关系。您想要将该表示转换为标准的“树形”表示。更多有关数据模型理论的信息: http://www.phpriot.com/articles/nested-trees-1 以下是实现方法:创建一个名为“ TreeNode”的类:
class TreeNode {
     public $commendId;
     public $arrChildren;
}

接下来,遍历从数据库中获取的数组。逐个处理每个项目,并在处理项目时创建TreeNodes。您可以使用深度优先或广度优先的方法查找父节点并将节点附加到其上。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接