1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51:
<?php $data[] = array('name' => 'h', 'list' => array(1,2)); $data[] = array('name' => 'g', 'list' => array(1)); $data[] = array('name' => 'a', 'list' => array(1,3)); $data[] = array('name' => 'f', 'list' => array(2)); $data[] = array('name' => 'e', 'list' => array(2,3)); $data[] = array('name' => 'b', 'list' => array(3)); $data[] = array('name' => 'c', 'list' => array(1,2,3,4)); $data[] = array('name' => 'd', 'list' => array(3,4)); function deep_sort($array, $sorton){ usort($array, function($a, $b) use($sorton) { $a = $a[$sorton]; $b = $b[$sorton]; if(is_array($a) && is_array($b)){ // this bit is obviously flawed - only included for illustrative purposes $a = implode('', $a); $b = implode('', $b); } return ($a == $b) ? 0 : ($a > $b) ? 1 : -1; }); return $array; } $sorted_by_name = deep_sort($data, 'name'); print '<pre>'; print_r($sorted_by_name); print '</pre>'; $sorted_by_list = deep_sort($data, 'list'); print '<pre>'; print_r($sorted_by_list); print '</pre>'; ?>
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67:
<?php // RAY_temp_usort.php error_reporting(E_ALL); echo "<pre>"; // TEST DATA FROM THE POST AT EE $data[] = array('name' => 'h', 'list' => array(1,2)); $data[] = array('name' => 'g', 'list' => array(1)); $data[] = array('name' => 'a', 'list' => array(1,3)); $data[] = array('name' => 'f', 'list' => array(2)); $data[] = array('name' => 'e', 'list' => array(2,3)); $data[] = array('name' => 'b', 'list' => array(3)); $data[] = array('name' => 'c', 'list' => array(1,2,3,4)); $data[] = array('name' => 'd', 'list' => array(3,4)); // A FUNCTION TO COMPARE BY NAMES function cmp_name($a, $b) { if ($a["name"] == $b["name"]) return 0; return ($a["name"] < $b["name"]) ? -1 : 1; } // A FUNCTION TO COMPARE BY GROUPS function cmp_group($a, $b) { if ($a["group"] == $b["group"]) return 0; return ($a["group"] < $b["group"]) ? -1 : 1; } // COPY ARRAY AND SORT ON NAME $test = $data; usort($test, 'cmp_name'); // SHOW THE WORK PRODUCT var_dump($test); // COPY THE ARRAY AND ADD GROUPS $test = $data; $maxlen = 0; foreach($test as $ptr => $arr) { $test[$ptr]['group'] = implode('', $arr['list']); if (strlen($test[$ptr]['group']) > $maxlen) $maxlen = strlen($test[$ptr]['group']); } // PAD THE GROUPS TO CONSISTENT LENGTH foreach ($test as $ptr => $arr) { $test[$ptr]['group'] = str_pad($test[$ptr]['group'], $maxlen+1, '0'); } // SORT ON GROUPS usort($test, 'cmp_group'); // REMOVE THE GROUPS (IF NEEDED) foreach ($test as $ptr => $arr) { unset($test[$ptr]['group']); } // SHOW THE WORK PRODUCT var_dump($test);