Sorting of 2D Array by Its Amount of in the Inner Elements

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], ...]

How to sort 2d array by row in python?

Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module array. There are third-party libraries such as numpy which do provide Python-usable multi-dimensional arrays, but of course you'd be mentioning such third party libraries if you were using some of them, rather than just saying "in Python", right?-)

So I'll assume that by "2d array" you mean a list of lists, such as:

lol = [ range(10), range(2, 12), range(5, 15) ]

or the like -- i.e. a list with 3 items, each item being a list with 10 items, and the "second row" would be the sublist item lol[1]. Yeah, lots of assumptions, but your question is so maddeningly vague that there's no way to avoid making assumptions - edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid.

So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example:

indices = range(10)
indices.sort(key = lol[1].__getitem__)
for i, sublist in enumerate(lol):
lol[i] = [sublist[j] for j in indices]

The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play.

If you actually have a different problem, there will of course be different solutions;-).

Sort a 2D array by the length of the inner array descending?

Surely there is! Python's sort has a key optional parameter which allows passing in a function to operate on and return some modified version of each item in the list to use for sorting.

The long-winded but easy to read way would be to define a function and pass it that:

def x(e):
return len(e)

my_list.sort(key=x)

but the one-liner way is to use a lambda (full working example down yonder):

l = [[],
[[23, 70, 90]],
[[23, 70, 90], [48, 56, 99]],
[[23, 70, 90], [48, 56, 99], [79, 89, 91]],
[[23, 70, 90], [79, 89, 91]],
[[48, 56, 99]],
[[48, 56, 99], [79, 89, 91]],
[[79, 89, 91]]]

def print_arr(a):
for x in a:
print(x)

print_arr(l)

# here she is!
l.sort(key=lambda x: len(x)) # add the optional 'reverse=True' param if desired

print_arr(l)

Sorting 2d Arrays containing Numbers and Strings

You may use the build in method Array#sort with a custom callback.

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

var arr1 = [[1, "Hair Pin"], [21, "Bowling Ball"], [2, "Dirty Sock"], [5, "Microphone"]];
arr1.sort(function (a, b) { return a[1].localeCompare(b[1]);});
document.write('<pre>' + JSON.stringify(arr1, 0, 4) + '</pre>');

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.



Related Topics



Leave a reply



Submit