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.

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); 

demo


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -