按两列对二维数组进行排序,均为降序[重复]

问题描述 投票:0回答:3

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

我有数组

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
    )
)
php arrays sorting multidimensional-array
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 有你想要的了。


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
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.