开发者

Ordering a PHP array

I have an php array (with comments) that has to be ordered differently.

The order of the array content should be like this...

parent
 child
  child
   child
parent
 child
  child
etc.

The parent comments have "parent = 0". The child comments have the id of their parent (e.g. "parent = 1"). The depth/amount of child comments is unknown.

How can get an array with the mentioned order when I have for example this kind of array?

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

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

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

    [3] => Array
   开发者_如何学JAVA     (
            [comment_id] => 4
            [parent] => 3
        )

)


Borrowed from my answer here. There's many similar questions you can check out.

Something like:

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


Let me guess: you have a database that stores "parent" relationships in every node. What you want is to convert that representation into a standard "tree" representation. More theory on the model in which you have your data: http://www.phpriot.com/articles/nested-trees-1

Here's how you can do it: create a class called "TreeNode":

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

Then, iterate through the array you got from the database. Go through each item, and create the TreeNodes are you're processing the items. You can use a depth-first or breadth-first approach to find the parent and attach the nodes to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜