PHP array order

I have a php array (with comments) that needs to be ordered in different ways.

The order of the contents of the array should be like this:

parent
 child
  child
   child
parent
 child
  child
etc.

Parent comments have "parent = 0". Child comments have an identifier for their parent (for example, "parent = 1"). Depth / number of comments for children is unknown.

How to get an array with the specified order when I have, for example, such an 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
        )

)
+3
source share
2 answers

Borrowed from my answer here . There are many similar questions you can check.

Sort of:

<?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);
?>
+1
source

, , "" node. "tree". , : http://www.phpriot.com/articles/nested-trees-1

: "TreeNode":

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

, . TreeNodes, . , .

0

Source: https://habr.com/ru/post/1785993/


All Articles