重新排序多维数组

时间:2016-04-20 01:05:04

标签: php sorting multidimensional-array

我有一个从DB表中读取的脚本

当前输出:

{ ["id"]=>"1" ["name"]=> "USER 1" ["parentID"]=>"0" }
{ ["id"]=>"7" ["name"]=> "USER 7" ["parentID"]=>"1" }
{ ["id"]=>"3" ["name"]=> "USER 3" ["parentID"]=>"1" }
{ ["id"]=>"6" ["name"]=> "USER 6" ["parentID"]=>"3" }
{ ["id"]=>"2" ["name"]=> "USER 2" ["parentID"]=>"3" }
{ ["id"]=>"5" ["name"]=> "USER 5" ["parentID"]=>"4" }
{ ["id"]=>"8" ["name"]=> "USER 8" ["parentID"]=>"5" }
{ ["id"]=>"9" ["name"]=> "USER 9" ["parentID"]=>"6" }
{ ["id"]=>"4" ["name"]=> "USER 4" ["parentID"]=>"7" }

我按照父ID的升序从数据库中读取,我需要对它们进行重新排序,以便子项位于父ID之下,因此例如USER 4应该在USER 7之后,因为USER 4具有父ID 7

预期输出:

{ ["id"]=>"1" ["name"]=> "USER 1" ["parentID"]=>"0" }    
{ ["id"]=>"7" ["name"]=> "USER 7" ["parentID"]=>"1" }    
{ ["id"]=>"4" ["name"]=> "USER 4" ["parentID"]=>"7" }    
{ ["id"]=>"3" ["name"]=> "USER 3" ["parentID"]=>"1" }    
{ ["id"]=>"6" ["name"]=> "USER 6" ["parentID"]=>"3" }    
{ ["id"]=>"2" ["name"]=> "USER 2" ["parentID"]=>"3" }    
{ ["id"]=>"5" ["name"]=> "USER 5" ["parentID"]=>"4" }    
{ ["id"]=>"8" ["name"]=> "USER 8" ["parentID"]=>"5" }    
{ ["id"]=>"9" ["name"]=> "USER 9" ["parentID"]=>"6" }

我的代码:

$list = [];
$db = Db::getInstance();

$req = $db->query('SELECT * FROM staff');

foreach($req->fetchAll() as $staff) {

    $data['id'] = $staff['ID'];
    $data['name'] = $staff['name'];
    $data['parentID'] = $staff['ParentID'];

    array_push($list,$data);
}

1 个答案:

答案 0 :(得分:0)

我建议您使用数据库查询来处理排序。

 SELECT * FROM staff ORDER BY id, parentID;