I have a multi-dimensional array and I want to sort it. The array looks like this:
$test_arr = [
/* artist albums tracks */
[ "Green Day", "8", "26", ],
[ "Remy Zero", "1", "2", ],
[ "System of a Down", "1", "1", ],
[ "Modern Talking", "1", "1", ],
[ "Snow Patrol", "1", "2", ],
[ "Linkin Park", "6", "18", ],
];
I want to sort the artists with respect to their albums and tracks numbers. To do that, I have created a function.
function sort_mul_dim_arr($mul_dim_arr, $sort_col) {
$control_arr = [];
for ($i = 0; $i < count($mul_dim_arr); $i++) {
array_push($control_arr, $mul_dim_arr[$i][$sort_col]);
}
sort($control_arr);
$sorted_arr = [];
for ($i = 0; $i < count($control_arr); $i++) {
for ($j = 0; $j < count($mul_dim_arr); $j++) {
if ($control_arr[$i] == $mul_dim_arr[$j][$sort_col]) {
array_push($sorted_arr, $mul_dim_arr[$j]);
}
}
}
return $sorted_arr;
}
$test_arr = sort_mul_dim_arr($test_arr, 0);
After sorting, the output ($test_arr) would look like this:
$test_arr = [
/* artist albums tracks */
[ "Green Day", "8", "26", ],
[ "Linkin Park", "6", "18", ],
[ "Modern Talking", "1", "1", ],
[ "Remy Zero", "1", "2", ],
[ "Snow Patrol", "1", "2", ],
[ "System of a Down", "1", "1", ],
];
But here's the problem. If the column I use to sort has unique values, function works fine. In the example, artist names are unique. But if I try to use albums or tracks columns to sort, function doesn't work. It messes up the array. Rows start to occur twice or more.
I have read some other questions about sorting multi-dimensional arrays, but they were talking about sorting in horizontal order. I need to sort in vertical order. How can I improve this function so I can sort with non-unique columns too? Or is there a PHP function to that already?