1

我需要按 [price] 的值对数组(较低)进行排序,但如果 [stock] = 0 的值,我也需要对它们进行排序,但它们的位置应低于 [stock] > 0 的值。函数有对于任意数量的子数组,数组 lower 只是示例。

我有数组

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

提前感谢您的帮助。

4

3 回答 3

3

好的,这就是你想要的:

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 有你想要的。

于 2013-10-04T14:35:04.897 回答
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');

这应该有效。首先比较价格,其次比较股票。

于 2013-10-04T14:09:05.860 回答
1

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);
于 2013-10-04T14:20:46.240 回答