简体   繁体   English

按值对数组排序PHP

[英]Sorting array by values PHP

I am sorting through an array using the usort function. 我正在使用usort函数对数组进行排序。 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. 模式继续...看来我没有考虑3位数字的排序。 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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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