【问题标题】:Ordering a PHP array订购 PHP 数组
【发布时间】:2011-06-10 17:21:44
【问题描述】:

我有一个必须以不同方式排序的 php 数组(带有 cmets)。

数组内容的顺序应该是这样的……

parent
 child
  child
   child
parent
 child
  child
etc.

父 cmets 有“parent = 0”。 子 cmets 具有其父级的 id(例如“parent = 1”)。 子 cmets 的深度/数量未知。

当我有这种数组时,如何获得具有上述顺序的数组?

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 次。

标签: php arrays tree hierarchy


【解决方案1】:

让我猜猜:您有一个数据库,在每个节点中存储“父”关系。您想要的是将该表示转换为标准的“树”表示。有关您拥有数据的模型的更多理论:http://www.phpriot.com/articles/nested-trees-1

您可以这样做:创建一个名为“TreeNode”的类:

class TreeNode {
     public $commendId;
     public $arrChildren;
}

然后,遍历从数据库中获得的数组。遍历每个项目,并在您正在处理项目时创建 TreeNode。您可以使用深度优先或广度优先的方法来查找父节点并将节点附加到它。

【讨论】:

    【解决方案2】:

    借用我的answer here。您可以查看许多类似的问题。

    类似:

    <?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);
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多