I need to sort some arrays wich keys are prices of products. I've used ksort
and krsort
and everything has worked as desired. The problem is when the number of the key has more than one figures, then it doesn't order propertly.
Array example:
$array = array(
'11,45' => 'product1',
'8,91' => 'product2',
'12,14' => 'product3',
'9,54' => 'product4
);
Result I got for order ascendent:
11,45 - 12,14 - 8,91 - 9,54
Result desired for order ascendent:
8,91 - 9,54 - 11,45 - 12,14
Use ksort
function with SORT_NUMERIC
flag:
ksort($array, SORT_NUMERIC);
This function might do the trick; it's based on splitting what is before the comma.
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);
This simple and short solution may help you.
$array = array(
'11.45' => 'product1',
'8.91' => 'product2',
'12.14' => 'product3',
'9.54' => 'product4'
);
$array=array_flip($array); //flip key and values
asort($array); //sort values low to high
$array=array_flip($array); //flip the key and values again
print_r($array);