如何以树格式卸载PHP数组?

时间:2014-01-20 19:39:58

标签: php arrays

我有一个基于用户1014的数组。所以就像金字塔一样,我想分别用1014之后的用户回应一棵树。

像:

$arr = array(

        1005 => 1014,
        1008 => 1014,

        1019 => 1008,
        1020 => 1008,
        1022 => 1005,
        1023 => 1005,
        );  

1014
     - 1005
     - 1022(这应该缩进超过1005)
     - 1023(这应该缩进超过1005)
     - 1008
     - 1019(这应该缩进超过1008)
     - 1020(这应该缩进超过1008)

1005和1008来自1014
1019和1020来自1008
1022和1023来自1005

等等......

我创建了一个从用户ID到顶部的功能,但不知道对面......

function get_rede($id_winner) {

global $link;

$precednt = array();
$precednt_id = array();

$result = mysqli_query($link, "SELECT rede FROM users WHERE id = '$id_winner' ");

$row = mysqli_fetch_row($result);   
$rede = $row[0]; 

array_push($precednt, $rede);
array_push($precednt_id, $id_winner);

do {

$q_precednt = end($precednt); 

$result = mysqli_query($link, "SELECT rede FROM users WHERE id = '$q_precednt' ");

$row = mysqli_fetch_row($result);   
$rede = $row[0]; 

array_push($precednt, $rede);
array_push($precednt_id, $q_precednt);

}
while($rede != 1000);

return array($precednt,$precednt_id);
}

谢谢!

嗯,这就是我追求的结果。想不出一个数组函数来帮助我。

enter image description here

1 个答案:

答案 0 :(得分:1)

<?php

$arr = array(
        1014 => 1003, 
        1003 => 1002, 
        1002 => 1000, 

        1005 => 1014,
        1008 => 1014,

        1019 => 1008,
        1020 => 1008,
        1022 => 1005,
        1023 => 1005,
        );

foreach ($arr as $key => $value) {
    $new_arr[$value][$key] = 1;
}

ksort($new_arr);

// here is your output 
$output = reorder($new_arr);

function reorder($new_arr)
{
    if (count($new_arr) == 1) return $new_arr;
    $tree_array = $new_arr;
    foreach ($new_arr as $key => $values) {
        foreach (array_keys($values) as $ak) {
            if (array_key_exists($ak, $new_arr)) {

                $values[$ak] = $new_arr[$ak];

                $tree_array[$key] = $values;
                unset($tree_array[$ak]);
            }
        }   
    }

    return reorder($tree_array);
}

这将输出:

Array
(
    [1000] => Array
        (
            [1002] => Array
                (
                    [1003] => Array
                        (
                            [1014] => Array
                                (
                                    [1005] => Array
                                        (
                                            [1022] => 1
                                            [1023] => 1
                                        )

                                    [1008] => Array
                                        (
                                            [1019] => 1
                                            [1020] => 1
                                        )

                                )

                        )

                )

        )

)

这假设您有一个根。