Jump to content

[SOLVED] cant work out usort function


dingus

Recommended Posts

ok basicly i have an array i need to sort that from the center out (0.5) and the order descending for example

 

0.5

0.7

0.1

 

given that 0.7 is only 2 away from 5 where 0.1 is 4

 

now to best of my knowledge usort would be the best way to do this but i have no idea how can anyone offer some light on this?

Link to comment
https://forums.phpfreaks.com/topic/102910-solved-cant-work-out-usort-function/
Share on other sites

Not sure that's possible with a usort function. My approach would be to cycle though the array, and calculate a distance from the centre and store this in an array. Associatively sort this array, then cycle through this array using the keys to put a new array in order:

 

<?php
$array = array(0.5,0.7,0.4,0.45,0.1,0.99);
foreach($array as $k=>$v){
    $temp[$k] = abs(0.5-$v);
}
asort($temp);
foreach($temp as $k=>$v){
    $sorted[] = $array[$k];
}
echo '<pre>'.print_r($sorted,1).'</pre>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.