Wednesday, 29 August 2018

PHP: Sort a multidimensional array, but keep its substructure

I have a multidimensional arrays with the following structure:

$arr[0][0] = 1.24;
$arr[0][1] = 5.21;
$arr[0][2] = 2.72;
$arr[0][3] = 1.89;
$arr[0][4] = 4.62;

$arr[1][0] = 3.45;
$arr[1][1] = 5.61;
$arr[1][2] = 2.62;
$arr[1][3] = 1.12;
$arr[1][4] = 1.35;

This array should get sorted while keeping the suborder of $arr[0] and $arr[1], so the result looks like this:
$arr[0][0] = 1.24;
$arr[1][0] = 3.45;
$arr[0][1] = 5.21;
$arr[0][2] = 2.72;
$arr[0][3] = 1.89;
$arr[0][4] = 4.62;
$arr[1][2] = 2.62;
$arr[1][3] = 1.12;
$arr[1][4] = 1.35;
$arr[1][1] = 5.61;

I do not care in which form the result get saved, but I need both keys and the value. Hope you understand and can help me.

How about looping the outer array and sorting the inner?
foreach ($arr as $id => $data) {
 sort($data);
 $arr[$id] = $data;
}

0 comments:

Post a Comment