【问题标题】:php usort multidimensional array order by price ascphp usort 多维数组 order by price asc
【发布时间】:2016-03-24 07:10:47
【问题描述】:

我有一个结构像这样的数组 $product_array 样本=

[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);

我错过了什么 谢谢

【问题讨论】:

标签: php arrays usort


【解决方案1】:

您在最后一个数组元素 ... [price] =&gt; 1,016.25 ... 中有一个格式不正确的数值。
这是一个“货币格式”,应该以字符串形式呈现:[price] =&gt; "1,016.25"。 另外,usort 参数也有一定的注意事项:

注意:从比较函数返回非整数值, 例如浮点数,将导致内部强制转换为整数 回调的返回值。所以像 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");

以上将按预期工作......

【讨论】:

    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2017-01-20
    • 2020-03-09
    相关资源
    最近更新 更多