ConFoo Montreal 2026: Call for Papers

Voting

: one plus seven?
(Example: nine)

The Note You're Voting On

centraleffects at yahoo dot com
12 years ago
I wrote this function to sort meta_value in wordpress. I tried a lot of array sorting but neither of them work. But this is not suitable for multidimensional array. This is intended only for wordpress meta_value

The problem is to sort below( the order should be ascending; alphabetically then numerically like A-Z then 0-9):
500-999 users
25-49 users
All Sizes
1-4 users
5-9 users
10-24 users
250-499 users
1000-4999
5000-9999

The solution:

function array_sort($arr){
if(is_array($arr)){
$numeric = array();
$string = array();
foreach($arr as $k => $v)
{
if(isset($v["meta_value"])){
$str = explode(" ",trim($v["meta_value"]));
$firstWord = explode("-",trim($str[0]));
}else{
$str = $v;
$firstWord = explode("-",trim($str));
}

$firstWord = $firstWord[0];

if(is_numeric($firstWord))
{
$numeric[(int)$firstWord] = $v;
}else{
$string[$firstWord] = $v;
}
unset($firstWord);
}
ksort($string,SORT_STRING);
ksort($numeric,SORT_NUMERIC);

return array_merge((array)$string, (array)$numeric);
}


return false;
}

The usage:
$meta =get_post_meta($post_id,$meta_key);
$sorted = array_sort($meta);

The result:
All Sizes
1-4 users
5-9 users
10-24 users
25-49 users
250-499 users
500-999 users
1000-4999
5000-9999

<< Back to user notes page

To Top