0

I have a a script that reads form a DB table

Current Output:

{ ["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" }

I read from the database in the ascending order for the parent ID, I need to reorder them so that a child will be below the parent ID so for instance USER 4 should be after USER 7 as USER 4 has the parent ID 7.

Expected Output:

{ ["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" }

My code:

$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);
}
Jeff
  • 12,555
  • 5
  • 33
  • 60
Richard Mc
  • 162
  • 1
  • 14

1 Answers1

0

I suggest you use the database query to handle the sort.

 SELECT * FROM staff ORDER BY id, parentID;
user2182349
  • 9,569
  • 3
  • 29
  • 41