Sort a Set of Multidimensional Arrays by Array Elements

Sort a set of multidimensional arrays by array elements

Do you want to order them by the value of the "int" key ?

Use uasort with a callback function :

function compare_by_int_key($a, $b) {
if ($a['int'] == $b['int']) {
return 0;
}
return ($a['int'] < $b['int']) ? -1 : 1;
}
uasort($arr, "compare_by_int_key");

How to Sort a Multi-dimensional Array by Value

Try a usort. If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:

function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}

usort($myArray, 'sortByOrder');

Starting in PHP 5.3, you can use an anonymous function:

usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});

With PHP 7 you can use the spaceship operator:

usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});

Finally, in PHP 7.4 you can clean up a bit with an arrow function:

usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);

To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.

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;
});

If you need to retain key associations, use uasort() - see comparison of array sorting functions in the manual.

How do I sort a multidimensional array by one of the fields of the inner array in PHP?

You need to use usort, a function that sorts arrays via a user defined function. Something like:

function cmp($a, $b)
{
if ($a["price"] == $b["price"]) {
return 0;
}
return ($a["price"] < $b["price"]) ? -1 : 1;
}

usort($yourArray,"cmp")

Sort multidimensional array based on 2nd element of the subarray

list.sort, sorted accept optional key parameter. key function is used to generate comparison key.

>>> sorted(lst, key=lambda x: x[1], reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

>>> sorted(lst, key=lambda x: -x[1])
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

>>> import operator
>>> sorted(lst, key=operator.itemgetter(1), reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

Sort php multidimensional array by sub-value

You can use the usort function.

function cmp($a, $b) {
return $a["mid"] - $b["mid"];
}
usort($arr, "cmp");

See it

java Arrays.sort 2d array

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
public int compare(double[] a, double[] b) {
return Double.compare(a[0], b[0]);
}
});

JAVA-8: Instead of that big comparator, we can use lambda function as following-

Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));

How to sort a two-dimensional array (2d array) by date in ruby on rails?

You can sort 2d arrays with sort_by method: sort_by sorts in ascending order by default. If you want it to be in descending order, just reverse the result.

array.sort_by{ |a| a.first }.reverse

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

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.

  1. x < 0: element_a should come before element_b
  2. x = 0: element_a and element_b are equal, the elements are not swapped
  3. x > 0: element_a should come after element_b


Related Topics



Leave a reply



Submit