Friday, June 14, 2024

multi sort array in PHP

<?php

// Example combined data array

$combined_data = [

    ['partno' => 'B456', 'wd' => '20240613', 'qty' => 5],

    ['partno' => 'A123', 'wd' => '20240612', 'qty' => 10],

    ['partno' => 'C789', 'wd' => '20240614', 'qty' => 8],

    ['partno' => 'A123', 'wd' => '20240612', 'qty' => 15],

    ['partno' => 'B456', 'wd' => '20240613', 'qty' => 2],

];


// Generalized comparison function for multi-key sorting

function multiKeyCompare($keys) {

    return function ($a, $b) use ($keys) {

        foreach ($keys as $key) {

            if ($a[$key] < $b[$key]) return -1;

            if ($a[$key] > $b[$key]) return 1;

        }

        return 0;

    };

}


// Define the keys to sort by

$keys = ['partno', 'qty']; // First sort by 'partno', then by 'qty'


// Sort the combined data array using the generalized comparison function

usort($combined_data, multiKeyCompare($keys));


// Print the sorted array

foreach ($combined_data as $item) {

    echo "Part No: " . $item['partno'] . ", WD: " . $item['wd'] . ", QTY: " . $item['qty'] . "<br>";

}

?>