Sorting multi-dimensional associative array in PHP -
i have php array looks this:
array (size=1) 'marriot' => array (size=7) 0 => string 'doc5.txt' (length=8) 1 => string 'test.txt' (length=8) 2 => string 'test1.txt' (length=9) 3 => string 'test2.txt' (length=9) 4 => string 'test3.txt' (length=9) 5 => array (size=1) 'special docs' => array (size=2) 0 => string 'doc4.txt' (length=8) 1 => string 'doc3.txt' (length=8) 6 => array (size=1) 'adocs' => array (size=0) empty
as can see, holds non-associative files, , 2 folders, "special docs" , "adocs". problem two-fold:
first, want move 2 folders top of array prominent in view. second, want sort folders alphabetically (i.e. put "adocs" above "special docs". have tried array_multisort without success , sort of stuck here. know how might achieve this?
thanks help.
example input
$dir = array( 0 => 'doc5.txt', 1 => 'test.txt', 2 => 'test1.txt', 3 => 'test2.txt', 4 => 'test3.txt', 5 => array( 'special docs' => array ( 0 => 'doc4.txt', 1 => 'doc3.txt' ) ), 6 => array( 'adocs' => array() ) );
1 level sorting
function cmp ($a,$b) { if (is_array($a)){ if (is_array ($b)) { return strnatcasecmp (key($a), key($b)); } else { return -1; } } else { if (is_array ($b)) { return 1; } else { return strnatcasecmp ($a, $b); } } }
example output
array ( [0] => array ( [adocs] => array ( ) ) [1] => array ( [special docs] => array ( [0] => doc4.txt [1] => doc3.txt ) ) [2] => doc5.txt [3] => test.txt [4] => test1.txt [5] => test2.txt [6] => test3.txt )
multi level sorting (unlimited)
function cmp (&$a,&$b) { if (is_array($a)){ usort($a[key($a)], 'cmp'); if (is_array ($b)) { return strnatcasecmp (key($a), key($b)); } else { return -1; } } else { if (is_array ($b)) { return 1; } else { return strnatcasecmp ($a, $b); } } } usort ($dir, 'cmp');
example output
array ( [0] => array ( [adocs] => array ( ) ) [1] => array ( [special docs] => array ( [0] => doc3.txt [1] => doc4.txt ) ) [2] => doc5.txt [3] => test.txt [4] => test1.txt [5] => test2.txt [6] => test3.txt )
Comments
Post a Comment