php - Sorting A Multi Dimensional Array (Understanding Usort and MultiSort) -
i have array multiple database tables merged array of information needed. want sort information alphabetically name , id if same name.
i viewed of following topics , not able produce working result.
- sort multi-dimensional array in php
- sorting multi-dimensional array
- sort multi-dimensional array in php
- http://php.net/manual/en/function.usort.php
my array sudo dump
array(3){ [0] => array(3){ ['id'] => "1", ['name'] => "slippery sasha", ['type'] => "electric eel" }, [1] => array(3){ ['id'] => "2", ['name'] => "viscious vipers", ['type'] => "snake" }, [2] => array(3){ ['id'] => "3", ['name'] => "finnic fox", ['type'] => "rabid fox" }, }
code attempt
// sort $sortbytypes = array('name', 'id', 'type'); usort($returnarray, function($a, $b) use($sortbytypes){ foreach($sortbytypes $field){ $sort = strnatcasecmp($a[$field], $a[$field]); if($sort !== 0){ break; } } return $sort; });
my intended dump
array(3){ [0] => array(3){ ['id'] => "3", ['name'] => "finnic fox", ['type'] => "rabid fox" }, [1] => array(3){ ['id'] => "1", ['name'] => "slippery sasha", ['type'] => "electric eel" }, [2] => array(3){ ['id'] => "2", ['name'] => "viscious vipers", ['type'] => "snake" }, }
bonus if can explain how works , doing sort array giving me better understanding of feature awesome!
you can use usort
as
usort($arr,function($a,$b){ $c = strcasecmp($a['name'], $b['name']); $c .= $a['id'] - $b['id']; return $c; }); print_r($arr);
Comments
Post a Comment