对条件进行排序

时间:2013-10-04 14:00:45

标签: php arrays sorting

我需要按[price]的值排序数组(下限)但是如果[stock]的值= 0,我也需要对它们进行排序,但它们应该低于[stock]>的那些。该函数必须适用于任意数量的子数组,较低的数组仅为示例。

我有阵列

Array
(
[0] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 5
        [shop] => cernyrytir.cz
    )

[1] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 20
        [price] => 9
        [shop] => mysticshop.cz
    )

[2] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 5
        [price] => 5
        [shop] => najada.cz
    )

[3] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 3
        [shop] => rishada.cz
    )
)

我需要数组:

Array
(
[2] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 5
        [price] => 5
        [shop] => najada.cz
    )

[1] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 20
        [price] => 9
        [shop] => mysticshop.cz
    )

[3] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 3
        [shop] => rishada.cz
    )

[0] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 5
        [shop] => cernyrytir.cz
    )
)

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

function cmp($a, $b) {

    if($a['stock'] == 0 && $b['stock'] != 0) 
        return -1;

    if($b['stock'] == 0 && $a['stock'] != 0) 
        return 1;

    if ($a['price'] == $b['price']) 
        return 0;


    return ($a['price'] < $b['price']) ? -1 : 1;
}



uasort($productsArr , 'cmp');

这应该有效。首先你比较价格,然后你比较股票。

答案 1 :(得分:2)

好的,这就是你想要的:

foreach($a as $key => $value) {
    if ($value['stock'] > 0) {
        $stock[] = $value;
        $stockPrice[] = $value['price'];
    } else {
        $zeroStock[] = $value;
        $zeroStockPrice[] = $value['price'];
    }
}

array_multisort($stockPrice, SORT_ASC, $stock);
array_multisort($zeroStockPrice, SORT_ASC, $zeroStock);

$array = array_merge($stock, $zeroStock);

现在$ array有你想要的东西。

答案 2 :(得分:0)

array_multisort()查看foreach的示例并保存两个数组$ stock和$ price并使用它们对主数组进行排序。

foreach ($array as $key => $row) {
    $stock[$key]  = $row['stock'];
    $price[$key] = $row['price'];
}
//adjust to fit asc or desc
array_multisort($price, SORT_DESC, $stock, SORT_DESC, $array);