Thursday, 30 August 2018

PHP sorting table based on three internal table key values


I am looking to do some complex array sorting, but I have no idea where to start. The inner array has three relevant keys for sorting: first the year (numerical ASC), then the month (numerical ASC) and finally the name (alphabetical DESC).


<?php
// the current array:
$array = (
  array('year'=>2012, 'month'=>3, 'name'=>'John', 'score'=>12),
  array('year'=>2013, 'month'=>8, 'name'=>'Paul', 'score'=>3),
  array('year'=>2013, 'month'=>5, 'name'=>'Dennis', 'score'=>7),
  array('year'=>2012, 'month'=>3, 'name'=>'Paul', 'score'=>5),
  array('year'=>2012, 'month'=>12, 'name'=>'Paul', 'score'=>9),
  array('year'=>2012, 'month'=>9, 'name'=>'Mitt', 'score'=>3)
);

// I want to do some sorting with this as output:
$array = (
  array('year'=>2012, 'month'=>3, 'name'=>'John', 'score'=>12),
  array('year'=>2012, 'month'=>3, 'name'=>'Paul', 'score'=>5),
  array('year'=>2012, 'month'=>9, 'name'=>'Mitt', 'score'=>3),
  array('year'=>2012, 'month'=>12, 'name'=>'Paul', 'score'=>9),
  array('year'=>2013, 'month'=>5, 'name'=>'Dennis', 'score'=>7),
  array('year'=>2013, 'month'=>8, 'name'=>'Paul', 'score'=>3)
);
?>

If anyone can point me in the right direction that is really appreciated ;-).

This should work...
<?php
    // Obtain a list of columns
    // PHP 5 >= 5.5.0
    $years  = array_column($array, 'year');
    $months = array_column($array, 'month');
    $names  = array_map('strtolower', array_column($array, 'name')); // because it's a string sort.

    // Sort the data with volume descending, edition ascending
    // Add $data as the last parameter, to sort by the common key
    array_multisort($years, SORT_ASC, $months, SORT_ASC, $names, SORT_DESC, $array);
?>

EDIT : for PHP < 5.5
<?php
    // Obtain a list of columns
    // PHP < 5.5.0
    foreach ($array as $key => $row) {
        $years[$key]  = $row['year'];
        $months[$key] = $row['month'];
        $names[$key]  = strtolower($row['name']); // because it's a string sort.
    }
?>

0 comments:

Post a Comment