php - Reorder multidimensional array -
i have a script reads form 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 database in ascending order parent id, need reorder them child below parent id instance user 4 should after user 7 user 4 has 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 * staff'); foreach($req->fetchall() $staff) { $data['id'] = $staff['id']; $data['name'] = $staff['name']; $data['parentid'] = $staff['parentid']; array_push($list,$data); }
i suggest use database query handle sort.
select * staff order id, parentid;
Comments
Post a Comment