繁体   English   中英

在PHP中的数组中对数组进行排序

[英]Sort array in array in array in PHP

我有这样的数组:

$items = array(
              [1] => array(
                           ['Name']   =>"Item 1", 
                           ['Prices'] => array(
                                               ['Base price'] => 80.25,
                                               ['Discount'] => 5.50
                                              )
                          ),

              [2] => array(
                           ['Name']   =>"Item 2", 
                           ['Prices'] => array(
                                               ['Base price'] => 70.25,
                                               ['Discount'] => 4.50
                                              )
                          )
              );

如何按“基本价格”对$ items进行排序? 我希望具有相同结构的输出数组的第一个元素的价格最低,最后一个元素的价格最高。

预期产量:

$items = array(
               [1] => array(
                           ['Name']   =>"Item 2", 
                           ['Prices'] => array(
                                               ['Base price'] => 70.25,
                                               ['Discount'] => 4.50
                                              )
                          ),
               [2] => array(
                           ['Name']   =>"Item 1", 
                           ['Prices'] => array(
                                               ['Base price'] => 80.25,
                                               ['Discount'] => 5.50
                                              )
                          )
              );

我不了解array_multisort()以及如何在我的情况下使用它。

这就是使用array_multisort

foreach ($items as $item) {
    $sort[] = $item['Prices']['Base price'];
}

array_multisort($sort, SORT_ASC, $items);

就像Jan所说的那样,您还可以使用usort

usort($items, function($a, $b) {
    return $a['Prices']['Base price'] - $b['Prices']['Base price'];
});

我希望这有帮助。 我将usort()与回调函数一起使用:

$arr = array(
    array(
        'foo' => 'bar',
        'data' => array(
            'basePrize' => 5
        )   
    ),
    array(
        'foo' => 'bar2',
        'data' => array(
            'basePrize' => 2
        )
    )
);

usort($arr, function($a, $b) {
    if($a['data']['basePrize'] === $b['data']['basePrize']) {
        return 0;
    }   

     if($a['data']['basePrize'] > $b['data']['basePrize']) {
        return 1;
    }   

    return -1
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM