Sort multidimensional array by multiple columns
You need array_multisort
$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);
# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);
As of PHP 5.5.0:
array_multisort(array_column($mylist, 'event_type'), SORT_DESC,
array_column($mylist, 'title'), SORT_ASC,
$mylist);
$mylist
is now:
array (
0 =>
array (
'ID' => 4,
'title' => 'Duct Tape Party',
'event_type' => 'party',
),
1 =>
array (
'ID' => 3,
'title' => 'Mario Party',
'event_type' => 'party',
),
2 =>
array (
'ID' => 1,
'title' => 'Boring Meeting',
'event_type' => 'meeting',
),
3 =>
array (
'ID' => 2,
'title' => 'Find My Stapler',
'event_type' => 'meeting',
),
)
How does one sort a multi dimensional array by multiple columns in JavaScript?
The array literal []
is preferred over new Array
. The notation {0,4,3,1}
is not valid and should be [0,4,3,1]
.
Is there a need for reinventing the wheel? Two arrays can be joined using:
originalArray = originalArray.concat(addArray);
Elements can be appended to the end using:
array.push(element);
Arrays have a method for sorting the array. By default, it's sorted numerically:
// sort elements numerically
var array = [1, 3, 2];
array.sort(); // array becomes [1, 2, 3]
Arrays can be reversed as well. Continuing the previous example:
array = array.reverse(); //yields [3, 2, 1]
To provide custom sorting, you can pass the optional function argument to array.sort()
:
array = [];
array[0] = [1, "first element"];
array[1] = [3, "second element"];
array[2] = [2, "third element"];
array.sort(function (element_a, element_b) {
return element_a[0] - element_b[0];
});
/** array becomes (in order):
* [1, "first element"]
* [2, "third element"]
* [3, "second element"]
*/
Elements will retain their position if the element equals an other element. Using this, you can combine multiple sorting algoritms. You must apply your sorting preferences in reverse order since the last sort has priority over previous ones. To sort the below array by the first column (descending order) and then the second column (ascending order):
array = [];
array.push([1, 2, 4]);
array.push([1, 3, 3]);
array.push([2, 1, 3]);
array.push([1, 2, 3]);
// sort on second column
array.sort(function (element_a, element_b) {
return element_a[1] - element_b[1];
});
// sort on first column, reverse sort
array.sort(function (element_a, element_b) {
return element_b[0] - element_a[0];
});
/** result (note, 3rd column is not sorted, so the order of row 2+3 is preserved)
* [2, 1, 3]
* [1, 2, 4] (row 2)
* [1, 2, 3] (row 3)
* [1, 3, 3]
*/
To sort latin strings (i.e. English, German, Dutch), use String.localeCompare
:
array.sort(function (element_a, element_b) {
return element_a.localeCompare(element_b);
});
To sort date's from the Date
object, use their milliseconds representation:
array.sort(function (element_a, element_b) {
return element_a.getTime() - element_b.getTime();
});
You could apply this sort function to all kind of data, just follow the rules:
x
is the result from comparing two values which should be returned by a function passed to array.sort
.
x < 0
:element_a
should come beforeelement_b
x = 0
:element_a
andelement_b
are equal, the elements are not swappedx > 0
:element_a
should come afterelement_b
How to sort multiple columns data in Multi-Dimensional array?
I also face the same issue and found a good solution for sort multiple columns data in Multi-Dimensional array.
Check the below code
(function() { function deepsort(){ var i, order= arguments, L= order.length, tem; return a.sort(function(a, b){ i= 0; while(i < L){ tem= order[i++]; var res = tem.split("_"); var ao= a[res[0]] || 0, bo= b[res[0]] || 0; if(ao== bo) continue; if(res[1] == "ASC"){ return ao > bo? 1: -1; } if(res[1] == "DESC"){ return ao < bo? 1: -1; } } return 0; });}
var a= [ ["2015-08-09", 1.2, 1.20, 2.1], ["2015-08-10", 1.2, 1.21, 2.11], ["2015-08-11", 1.2, 0.99, 2.20], ["2015-10-29", 1.2, 1.12, 2.22], ["2015-09-10", 1.21, 1.19, 2.00]];document.write(deepsort(1+"_ASC",2+"_ASC"));// for better result view check console logconsole.log(deepsort(1+"_ASC",2+"_ASC"))//console.log(a.deepsort(1)) })();
How to sort a multidimensional array by multiple columns?
Fundamentally we're going to use the same approach as explained here, we're just going to do it with a variable number of keys:
/**
* Returns a comparison function to sort by $cmp
* over multiple keys. First argument is the comparison
* function, all following arguments are the keys to
* sort by.
*/
function createMultiKeyCmpFunc($cmp, $key /* , keys... */) {
$keys = func_get_args();
array_shift($keys);
return function (array $a, array $b) use ($cmp, $keys) {
return array_reduce($keys, function ($result, $key) use ($cmp, $a, $b) {
return $result ?: call_user_func($cmp, $a[$key], $b[$key]);
});
};
}
usort($array, createMultiKeyCmpFunc('strcmp', 'foo', 'bar', 'baz'));
// or
usort($array, createMultiKeyCmpFunc(function ($a, $b) { return $a - $b; }, 'foo', 'bar', 'baz'));
That's about equivalent to an SQL ORDER BY foo, bar, baz
.
If of course each key requires a different kind of comparison logic and you cannot use a general strcmp
or -
for all keys, you're back to the same code as explained here.
C# sorting multidimensional array by multiple columns
Use a List<> object with Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication19
{
class Program
{
static void Main(string[] args)
{
List<List<int>> multiarray = new List<List<int>>{
new List<int> { 8, 63 },
new List<int> { 4, 2 },
new List<int> { 0, -55 },
new List<int> { 8, 57 },
new List<int> { 2, -120},
new List<int> { 8, 53 }
};
List<List<int>> sortedList = multiarray.OrderBy(x => x[1]).OrderBy(y => y[0]).ToList();
}
}
}
Sort an array of associative arrays by multiple columns using a combination of ascending, descending, regular, numeric, and natural sorting
I think you have to implement a custom comparison function for this behavior:
function myCmp($a, $b) {
$nameCmp = strnatcasecmp($a['Name'], $b['Name']);
$ageCmp = strnatcasecmp($a['Age'], $b['Age']);
$codeCmp = strnatcasecmp($a['Code'], $b['Code']);
if ($nameCmp != 0) // Names are not equal
return($nameCmp);
// Names are equal, let's compare age
if ($ageCmp != 0) // Age is not equal
return($ageCmp * -1); // Invert it since you want DESC
// Ages are equal, we don't need to compare code, just return the comparison result
return($codeCmp);
}
Then you can call usort($array, 'myCmp');
and should get the desired sorting
Sorting multi dimensional array by 2 columns - JavaScript
It is fairly straight forward:
If the strings are equal, then break the tie by comparing the integer values, else return the result of localeCompare
var arr = [
['ABC', 87, 'WHAT'],
['ABC', 34, 'ARE'],
['DEF', 13, 'YOU'],
['ABC', 18, 'DOING'],
['ABC', 34, 'DOING'],
['DEF', 24, 'TODAY'],
['ABA', 18, 'TODAY'],
['ABA', 11, 'TODAY']
];
function doSort(ascending) {
ascending = typeof ascending == 'undefined' || ascending == true;
return function(a, b) {
var ret = a[0].localeCompare(b[0]) || a[1] - b[1];
return ascending ? ret : -ret;
};
}
// sort ascending
arr.sort(doSort());
// sort descending
arr.sort(doSort(false));
Fiddle
PHP Sort Multidimensional Array Based on Multiple Criteria
I found a solution that uses array_multisort()
foreach ($arr as $key => $row) {
$wins[$key] = $row[1];
$losses[$key] = $row[2];
$ptsfor[$key] = $row[3];
}
array_multisort($wins, SORT_DESC, $losses, SORT_ASC, $ptsfor, SORT_DESC, $arr);
sort 2D array based on two columns
You can sort with your custom comparator:
Arrays.sort(datas, new Comparator<Integer[]>() {
@Override
public int compare(Integer[] entry1, Integer[] entry2) {
if(entry1[0] == entry2[0]){
return entry2[1] - entry1[1];
}
return entry2[0] - entry1[0];
}
});
Related Topics
PHP Variable Variables with Array Key
Add New Data into PHP JSON String
PHP Preg-Replace More Than One Underscore
I18N with Gettext But Without the Locale Hassle
Find and Replace Keywords by Hyperlinks in an HTML Fragment, via PHP Dom
Prevent Browser Back Button Cache
How to Render Content from String/Database with Twig
PHP Passing Parameters via Url
Laravel Access Denied for User 'Root'@'Localhost' (Using Password: Yes) in Laravel 4.2
The Ultimate Emoji Encoding Scheme
Php: How to Convert Bigint from Int to String
Codeigniter PHP Stylesheet Link. How