PHP array sort and remove duplicates by two field values



PHP Snippet 1:

foreach ($data as $da) {
    $result[$da['Number'] . '.' . $da['Location']] = $da;
}
$result = array_values($result); // Turn it back into indexed array

PHP Snippet 2:

 <?php
    $array = array(
        0 => array('Number'=>'L1','Location'=>'Location-A','Qty'=>'1'),
        1 => array('Number'=>'L1','Location'=>'Location-B','Qty'=>'5'),
        2 => array('Number'=>'L1','Location'=>'Location-B','Qty'=>'4'),
        3 => array('Number'=>'L2','Location'=>'Location-B','Qty'=>'5'),
    );
    $output =   array_values(array_intersect_key($array,array_unique(array_map(function($arrayval) {
        return $arrayval['Number'] . '.' .$arrayval['Location'];
    }, $array))
));
    print_r($output);

PHP Snippet 3:

Array ( [0] => Array ( [Number] => L1 [Location] => Location-A [Qty] => 1 )
        [1] => Array ( [Number] => L1 [Location] => Location-B [Qty] => 5 ) 
        [2] => Array ( [Number] => L2 [Location] => Location-B [Qty] => 5 ) )

PHP Snippet 4:

function array_unique_c($array, Closure $comparer) {
    $result = array();
    for($i = 0; $i < count($array); $i++) {
        $duplicates = false;
        for($n = $i + 1; $n < count($array); $n++) {
            if ($comparer($array[$i], $array[$n])) {
                $duplicates = true;
                break;
            }
        }
        if(!$duplicates) {
            $result[] = $array[$i];
        }
    }

    return $result;
}

PHP Snippet 5:

$uniqueArray = array_unique_c($a, function ($itemA, $itemB) {
    return $itemA['Number'] == $itemB['Number'] && $itemA['Location'] == $itemB['Location'];
});

PHP Snippet 6:

array(3) {
    [0] => array(3) {
        ["Number"] => string(2) "L1"
        ["Location"] => string(10) "Location-A"
        ["Qty"] => string(1) "1"
    }
    [1] => array(3) {
        ["Number"]=> string(2) "L1"
        ["Location"]=> string(10) "Location-B"
        ["Qty"]=> string(1) "4"
    }
    [2]=> array(3) {
        ["Number"]=> string(2) "L2"
        ["Location"]=> string(10) "Location-B"
        ["Qty"]=> string(1) "5"
    }
}

PHP Snippet 7:

$data = [
    ["Number"=> "L1","Location"=> "Location-A","Qty"=>"1"],
    ["Number"=> "L2","Location"=> "Location-B","Qty"=>"6"],
    ["Number"=> "L3","Location"=> "Location-A","Qty"=>"8"],
    ["Number"=> "L2","Location"=> "Location-B","Qty"=>"5"],
    ["Number"=> "L3","Location"=> "Location-A","Qty"=>"2"],
    ["Number"=> "L1","Location"=> "Location-B","Qty"=>"4"],
    ["Number"=> "L1","Location"=> "Location-B","Qty"=>"1"],
    ["Number"=> "L2","Location"=> "Location-B","Qty"=>"3"],
];

foreach ($data as $k=>$v) {
    $arr[md5($v['Number'].$v['Location'])] = $v;
}

$result = array_values($arr); //can be omitted