John Davidson

PHP - Sort multi-dimensional array of number arrays

0 comments
Message:


I have an array:


$arr = [
[4,6],
[1,2,3],
[7,8,9]
];

I'd like to sort it so the result is


$arr = [
[1,2,3],
[4,6],
[7,8,9]
];

If I apply sort($arr), it first sorts by array length and then compares the values. So I get


$arr = [
[4,6],
[7,8,9],
[1,2,3],
];

which is wrong for my purposes.


I could use a sorting algorithm to compare the elements.


Or I could create another array with each element imploded and then sort it.


But was wondering if there was an inbuilt or quicker way of getting this?


Thanks



My Answer:
You can use the usort function in PHP to achieve the desired sorting of the multi-dimensional array of number arrays. Here's an example code snippet to sort the array as per your requirements:

php
$arr = [
[4,6],
[1,2,3],
[7,8,9]
];

usort($arr, function($a, $b) {
if (count($a) == count($b)) {
return $a[0] - $b[0];
}
return count($a) - count($b);
});

print_r($arr);


This code snippet uses the usort function to sort the array based on the length of the subarrays first and then compares the values within the subarrays. This will give you the desired output:


Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)

[1] => Array
(
[0] => 4
[1] => 6
)

[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)

)


This will sort the array as per your requirements without having to implement a custom sorting algorithm or creating another array.

Rate this post

3 of 5 based on 3255 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us