PHP排序关联多维数组

抢劫

我有一个带有子数组的大数组,上面有子数组。

该方案是这样的:

$bigArray['apple'][]  = array('shop1', 'Fruit', '7');
$bigArray['apple'][]  = array('shop2', 'Fruit', '5');
$bigArray['pear'][]   = array('shop2', 'Fruit', '3.5');
$bigArray['banana'][] = array('shop1', 'Fruit', '2');

因此,在这种情况下$bigArray['apple']包含2个数组。

第一件事是,我想按升序(最低价格到最高价格)从第三个参数(价格)对数组进行排序,因此在打印时将显示:

'shop2', 'Fruit', '5' ->lowest price
'shop1', 'Fruit', '7'

第二件事是,我想$bigArray按升序对整个数组进行排序(再次从最低价格到最高价格);现在,由于$bigArray['apple']已经对like数组进行了排序,因此在$bigArray排序中仅$bigArray['apple'][0]考虑第一个数组,因为[0]将是已排序此子数组的最低价格。因此最终在打印时$bigArray将显示:

'shop1', 'Fruit', '2'
'shop2', 'Fruit', '3.5'
'shop2', 'Fruit', '5'
....

我一直在努力使用usort,但要处理多维关联数组要复杂得多。

谢谢你。

马尔辛·纳比亚列克(MarcinNabiałek)

我认为这是您想要实现的解决方案:

<?php

$bigArray['apple'][]  = array('shop1', 'Fruit', '7');
$bigArray['apple'][]  = array('shop2', 'Fruit', '5');
$bigArray['pear'][]   = array('shop2', 'Fruit', '3.5');
$bigArray['banana'][] = array('shop1', 'Fruit', '2');



foreach ($bigArray as &$item)  {

    uasort($item, function($a, $b) {        
        if ($a[2] == $b[2]) {
            return 0;
        }    

        return ($a[2] < $b[2]) ? -1 : 1;    

    });
}

uasort($bigArray, function($a, $b) { 
    if ($a[0][2] == $b[0][2]) {
        return 0;
    }    

    return ($a[0][2] < $b[0][2]) ? -1 : 1;    
});

foreach ($bigArray as $k => $v) {

    foreach ($v as $item)
    {
        echo $k.': '.$item[0].' '.$item[1].' '.$item[2]."<br />";            
    }

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章