/ Gists / Sort array by multiple values
On gists

Sort array by multiple values

Popular ⭐ PHP

sort.php Raw #

<?php

// https://blog.martinhujer.cz/clever-way-to-sort-php-arrays-by-multiple-values/
// https://stackoverflow.com/questions/2699086/how-to-sort-a-multi-dimensional-array-by-value
// COMPLEX: https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php
// https://stackoverflow.com/questions/44309585/properly-sorting-multidimensional-array-using-usort-and-spaceship-operator/44309755#44309755

// 1)
// order products by: price ASC, inStock DESC, isRecommended DESC, name ASC
usort($products, function (Product $a, Product $b): int {
    return
        ($a->getPrice() <=> $b->getPrice()) * 1000 + // price ASC
        ($b->isInStock() <=> $a->isInStock()) * 100 + // inStock DESC
        ($b->isRecommended() <=> $a->isRecommended()) * 10 + // isRecommended DESC
        ($a->getName() <=> $b->getName()); // name ASC
});


// 2) 
// order products by: price ASC, inStock DESC, isRecommended DESC, name ASC
usort($products, fn (Product $a, Product $b): int =>
    ($a->getPrice() <=> $b->getPrice()) * 1000 + // price ASC
    ($b->isInStock() <=> $a->isInStock()) * 100 + // inStock DESC
    ($b->isRecommended() <=> $a->isRecommended()) * 10 + // isRecommended DESC
    ($a->getName() <=> $b->getName()) // name ASC
);

// 3)
usort($products, fn (Product $a, Product $b): int =>
    [$a->getPrice(), $b->isInStock(), $b->isRecommended(), $a->getName()]
    <=>
    [$b->getPrice(), $a->isInStock(), $a->isRecommended(), $b->getName()]
);



usort($myArray, function($a, $b) {
    $retval = $a['order'] <=> $b['order'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

By-priority.php Raw #

<?php
// https://stackoverflow.com/questions/25603313/usort-multisort-array-based-on-another-array/61119066#61119066


$sortLike=array(60007,60001,60003,60002);
$array1= array(
    array ('ID' => 138,'zip_code' => 60007,'approved' => 1),
    array('ID' => 103,'zip_code' => 60007,'approved' => 0),
    array('ID' => 114,'zip_code' => 60007,'approved' => 1),
    array('ID' => 105,'zip_code' => 60003,'approved' => 0),
    array('ID' => 124,'zip_code' => 60002,'approved' => 0)
)


// PHP 5+ plus little messy code
function sort_results ($a, $b) {
    $sortLike=array(60007,60001,60003,60002);
    if (!in_array ($a['zip_code'], $sortLike)) { return 1; } // Push unknown values at the end of the array
    $zip_res = array_search($a['zip_code'], $sortLike) - array_search($b['zip_code'], $sortLike); // check zip_code order 
    if($zip_res == 0){ // if the zip_codes are equal
        $zip_res = $b['approved'] - $a['approved']; // sort by the 'approved' key
    }
    return $zip_res;
}

// or lambda
$sort_results = function ($a, $b) use ($sortLike){ // create lambda function with "use" keyword
    if (!in_array ($a['zip_code'], $sortLike)) { return 1; } // Push unknown values at the end of the array
    $zip_res = array_search($a['zip_code'], $sortLike) - array_search($b['zip_code'], $sortLike);
    if($zip_res == 0){
        $zip_res = $b['approved'] - $a['approved'];
    }
    return $zip_res;
};


// < PHP 7.4
$priorityZips = array_flip([60007, 60001, 60003, 60002]);
$priorityCount = count($priorityZips);

usort($rows, function($a, $b) use ($priorityZips, $priorityCount) {
    return [
               $priorityZips[$a['zip_code']] ?? $priorityCount,
               $a['zip_code'],
               $b['approved']
           ]
           <=>
           [
               $priorityZips[$b['zip_code']] ?? $priorityCount,
               $b['zip_code'],
               $a['approved']
           ];
});


// >= 
usort($rows, fn($a, $b) =>
    [
        $priorityZips[$a['zip_code']] ?? $priorityCount,
        $a['zip_code'],
        $b['approved']
    ]
    <=>
    [
        $priorityZips[$b['zip_code']] ?? $priorityCount,
        $b['zip_code'],
        $a['approved']
    ]
);


// or multisort , PHP 7.4 lower / higher

array_multisort(
    array_map(
        function($row) use ($priorityZips, $priorityCount) {
            return $priorityZips[$row['zip_code']] ?? $priorityCount;
        },
        $rows
    ),
    array_column($rows, 'zip_code'),
    array_column($rows, 'approved'),
    SORT_DESC,
    $rows
);



array_multisort(
    array_map(
        fn($row) => $priorityZips[$row['zip_code']] ?? $priorityCount,
        $rows
    ),
    array_column($rows, 'zip_code'),
    array_column($rows, 'approved'),
    SORT_DESC,
    $rows
);