Answer the question
In order to leave comments, you need to log in
How to sort an array by nearest number?
There is an array
$arr = array(
array('id'=>1,'value'=>4),
array('id'=>2,'value'=>6),
array('id'=>3,'value'=>2.5),
array('id'=>4,'value'=>-2),
array('id'=>5,'value'=>3),
array('id'=>6,'value'=>2.6),
array('id'=>7,'value'=>3),
array('id'=>8,'value'=>3),
array('id'=>9,'value'=>-3),
);
usort($arr, function($a, $b){
$c_v = 2.6;
return abs(($a['value'] - $c_v) - ($b['value'] - $c_v)); // тут возможно бред - уже изменял 100000 раз и запутался
});
array('id'=>6,'value'=>2.6),
array('id'=>3,'value'=>2.5),
array('id'=>6,'value'=>4),
array('id'=>5,'value'=>3),
array('id'=>7,'value'=>3),
array('id'=>8,'value'=>3),
.........
Answer the question
In order to leave comments, you need to log in
return abs(($a['value'] - $c_v) - ($b['value'] - $c_v)); // тут возможно бред - уже изменял 100000 раз и запутался
usort($arr, function($a, $b){
$c_v = 2.6;
return ceil(abs($a['value'] - $c_v) - abs($b['value'] - $c_v));
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question