我有一个像这样结构的数组 $ product_array sample =
[0] => Array
(
[title] => M-SPA Super Camaro B-150 6-Person Inflatable Bubble Spa
[image] => http://ecx.images-amazon.com/images/I/41F6FuitoYL._SL160_.jpg
[link] => http://www.amazon.com/stuff
[price] => 960.01
[merchant] => amazon
[discount] => 16
[brand] => M-SPA
)
[1] => Array
(
[title] => M Spa Model B-130 Camaro Hot Tub, 71 by 71 by 28-Inch, Gray
[image] => http://ecx.images-amazon.com/images/I/41zQwjaPqOL._SL160_.jpg
[link] => http://www.amazon.com/stuff
[price] => 695.01
[merchant] => amazon
[discount] =>
[brand] => M-SPA
)
[2] => Array
(
[title] => M-SPA B-121 4-Person Inflatable Bubble Spa, Castello
[image] => http://ecx.images-amazon.com/images/I/41gnYSSVD5L._SL160_.jpg
[link] => http://www.amazon.com/stuff
[price] => 1,016.25
[merchant] => amazon
[discount] =>
[brand] => M-SPA
)
我不能以最低到最高的价格订购这个数组。 此代码无效
function order_by_price($a, $b) {
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
}
usort($product_array,order_by_price);
我错过了什么 感谢
答案 0 :(得分:0)
您在最后一个数组元素... [price] => 1,016.25 ...
中有一个格式不正确的数字。
它是&#34; 货币格式&#34;并应以字符串形式显示:[price] => "1,016.25"
。
此外,usort
参数有一定的注意事项:
警告:从比较函数返回非整数值, 比如float,会导致内部强制转换为整数 回调的回报值。因此,诸如0.99和0.1之类的值都将是 强制转换为0的整数值,这将比较这些值 相等。
正确替换(格式化)后,如下所示更改代码:
function order_by_price($a, $b) {
$floats = str_replace(",", "", [$a['price'], $b['price']]);
return ($floats[0] == $floats[1])? 0 : (($floats[0] < $floats[1]) ? -1 : 1);
}
usort($product_array,"order_by_price");
以上将按预期工作......