php - Sorting Multidimensional array of more than one level -
i checked other question regarding sort multidimensional array none of them worked in case array following , want sort on based of id value in descending order
$arr = array( 49 => array( 'id' => 65, 'name' => 'any', 'users' => array( 772 => array( 'id' => 149, 'name' => 'any1' ), 771 => array( 'id' => 779, 'name' => 'any2' ), 45 => array( 'id' => 259, 'name' => 'any3' ) ) ), 789 => array( 'id' => 892, 'name' => 'any4', 'users' => array( 65 => array( 'id' => 389, 'name' => 'any5' ), 98 => array( 'id' => 895, 'name' => 'any6' ), 99 => array( 'id' => 899, 'name' => 'any7' ) ) ) );
i tried sort using usort function
usort($arr, function($a, $b) { return $b['id'] - $a['id']; });
but requirement sort parent child array sort parents
since rules sorting same both parents , children defined compare function. need loop on each parent , sort children.
//compare function, sorts id in desc order function cmp($a, $b){ return $b['id'] - $a['id']; } //loop on each parent reference changes value in parent array foreach($arr &$parent){ //sort children uasort($parent['users'], 'cmp'); } //unset parent array don't overwrite last parent later unset($parent); //sort parents uasort($arr, 'cmp'); demo: http://codepad.viper-7.com/hqm122
edit: added requirement of preserving keys. switched usort uasort.
Comments
Post a Comment