如何在 PHP 中从反向数组创建列表


how to create a list from a reversed array in php

我使用 jQuery nestedSortable Plugin ,每当项目更改顺序时,它都会返回项目列表。因此,从如下所示的列表中:

Item 371
Item 372
    Item 373
    Item 374
Item 375

我收到以下数组:

'0' ...
    'id' => "371"
    'parent_id' ...
    'depth' => "0"
    'has_child' => "0"
'1' ...
    'id' => "373"
    'parent_id' => "372"
    'depth' => "1"
    'has_child' => "0"
'2' ...
    'id' => "374"
    'parent_id' => "372"
    'depth' => "1"
    'has_child' => "0"
'3' ...
    'id' => "372"
    'parent_id' ...
    'depth' => "0"
    'has_child' => "1"
'4' ...
    'id' => "375"
    'parent_id' ...
    'depth' => "0"
    'has_child' => "0"

我现在正在做的是我存储每个项目的优先级(array no)。

问题是,通过提供的数组,子项获得比其父项(在上面的示例中3)更高的优先级(在上面的示例中12)。

现在,这使得每当重新加载视图时都无法重新创建列表,因为子项将在父项之前回显。

有没有其他方法可以从这个数组中重新创建列表?

编辑

元素不能有孙子,depth只能是01.

这种方法怎么样(其中$list是你给定的数组):

$queue=array();
foreach($list as $v){
    if($v['parent_id']==0){
        echo 'Item '.$v['id'];
        foreach($queue as $child){
            echo ': Item '.$child['id'];
        }
        $queue=array();
    }
    else {
        $queue[]=$v;    
    }
}