Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        )

)
like image 954
Jennifer Avatar asked Mar 12 '26 22:03

Jennifer


1 Answers

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);
?>
like image 189
Matthew Avatar answered Mar 14 '26 11:03

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!