订购PHP数组 [英] Ordering a PHP array

查看:159
本文介绍了订购PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP阵列(评论),有以不同方式订购。

数组内容的顺序应该是这样的...

 
 儿童
  儿童
   儿童

 儿童
  儿童
等等

家长的意见有父= 0。
孩子的意见有其父母的ID(例如,父​​= 1)。
小孩评论的深度/金额不详。

当我有例如这种阵列如何可以得到该顺序数组?

 阵列

    [0] =>排列
        (
            [COMMENT_ID] => 1
            [家长] => 0
        )    [1] =>排列
        (
            [COMMENT_ID] => 2
            [家长] => 0
        )    [2] =>排列
        (
            [COMMENT_ID] => 3
            [家长] => 1
        )    [3] =>排列
        (
            [COMMENT_ID] => 4
            [家长] => 3
        ))


解决方案

从我<借用的href=\"http://stackoverflow.com/questions/3827340/convert-2d-array-into-3d-with-php/3827593#3827593\">answer这里。还有很多类似的问题,你可以查一下。

是这样的:

 &LT; PHP
$ p值=阵列(0 =&GT;阵列());
的foreach(如$ N $节点)
{
  $ PID = $ N ['父'];
  的$ id = $ N ['COMMENT_ID'];  如果(!使用isset($ P [$ PID))
    $ P [$ PID =阵列('孩子'=&GT;阵());  如果(使用isset($ P [$ ID]))
    $孩子=安培; $ P [$ ID] ['孩子'];
  其他
    $孩子=阵列();  $ P [$ ID] = $ N;
  $ P [$ ID] ['孩子'] =&放大器; $子女;
  未设置($ P [$ ID] ['父']);
  未设置($子女);  $ P [$ PID] ['孩子'] [] =&放大器; $ P [$ ID];
}
$节点= $ P [0] ['孩子'];
未设置($ P);
?&GT;

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
        )

)

解决方案

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

这篇关于订购PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆