Jennifer
Jennifer

Reputation: 217

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
        (
            [comment_id] => 4
            [parent] => 3
        )

)

Upvotes: 3

Views: 267

Answers (2)

Matthew
Matthew

Reputation: 48284

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

Upvotes: 1

Alex Weinstein
Alex Weinstein

Reputation: 9891

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.

Upvotes: 0

Related Questions