Ordering a PHP array

夙愿已清 提交于 2019-12-12 14:52:11

问题


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
        )

)

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4718058/ordering-a-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!