简体   繁体   中英

Sorting array by values PHP

I am sorting through an array using the usort function. The loop is working correctly as is the sorting (to some degree) however I seem to have missed something with regards to decimal places etc. My function is below

usort($this->view->blogs, 'comparison');

And here is the function. The function call works correctly and I can see I am returned sorted data

function comparison($a, $b)
{
    return strcmp($a->cost_per_blog, $b->cost_per_blog);
}

The issue is with the actual sorting logic for instance I am returned a list like below

0.09724
0.58344
1.16688
12.05776
120.5776
126.60648
13.22464
132.63536
138.66424
168.80864
18.08664
18.08664
18.67008
180.8664
19.25352
21.10108
22.26796

the pattern continues... It appears that I am not taking into account the sorting of 3 digit numbers. I cant seem to think of what I am missing. Any help would be greatly appreciated.

然后不要比较字符串,比较数字:

return $a->cost_per_blog - $b->cost_per_blog;

您将它们比较为字符串而不是双精度。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM