需要在多个键中通过重复值组合PHP数组

时间:2018-06-09 23:02:04

标签: php arrays mergesort

我有一个超过1000个值的数组。这个数组是在一个php文件中,我将结果返回另一个数组输出到excel文件。非常感谢协助

Array
(
[0] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => PXB
        [low] => 24.99
    )
[1] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => PXB
        [low] => 31.99
    )
[2] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => PXB
        [low] => 38.99
    )
[3] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => MXB
        [low] => 24.99
    )
[4] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => MXB
        [low] => 31.99
    )
[5] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => MXB
        [low] => 38.99
    )
[6] => Array
    (
        [isbn] => 97845684978
        [price] => 30.99
        [po] => PXB
        [low] => 18.99
    )
[7] => Array
    (
        [isbn] => 97845684978
        [price] => 30.99
        [po] => PXB
        [low] => 19.99
    )
[8] => Array
    (
        [isbn] => 97845684978
        [price] => 30.99
        [po] => PXB
        [low] => 23.99
    )
)

我需要能够对数组进行排序并返回一个输出,每个输出具有一个isbn,保持该po的最低值为low。我需要按isbn,po和low排序。所以我正在寻找输出:

 Array
(
[0] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => PXB
        [low] => 24.99
    )
[1] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => MXB
        [low] => 31.99
    )
[2] => Array
    (
        [isbn] => 97845684978
        [price] => 30.99
        [po] => PXB
        [low] => 18.99
    )
[3] => Array
    (
        [isbn] => 97845684684
        [price] => 30.99
        [po] => MXB
        [low] => 15.99
    )

1 个答案:

答案 0 :(得分:1)

使用usort过滤低位:

$array = //your array

function cmp($a, $b) {
    if ($a['po'] == $b['po'] && $a['isbn'] == $b['isbn']) {
       return ($a['low'] < $b['low']) ? -1 : 1;
    }else{
        return 0;
    }

}

usort($array, 'cmp');

Foreach循环重新填充数组。

$po = null;
$isbn = null;
$result = [];
foreach($array as $key =>$val){    
    if($val['po']==$po && $val['isbn']==$isbn){
    }else{
        $result[] = $val; 
    }
    $isbn = $val['isbn'];
    $po = $val['po'];
}
echo '<pre>';
print_r($result);
echo '</pre>';