Reputation: 12175
I'm trying to figure out how to sort an array, that has sub arrays which each have an X & Y coordinate. I need to sort the largest size first to the smallest, example:
$sizes = array(
'a' => array(
'x' => 10,
'y' => 140,
),
'b' => array(
'x' => 20,
'y' => 24,
),
'c' => array(
'x' => 20,
'y' => 40,
),
'd' => array(
'x' => 50,
'y' => 50,
),
'e' => array(
'x' => 10,
'y' => 9,
),
);
Should resort naturally like so:
$sizes = array(
'e' => array(
'x' => 10,
'y' => 9,
),
'b' => array(
'x' => 20,
'y' => 24,
),
'c' => array(
'x' => 20,
'y' => 40,
),
'd' => array(
'x' => 50,
'y' => 50,
),
'a' => array(
'x' => 10,
'y' => 140,
),
);
I've sorted by value before using asort, however I'm not sure how to sort and maintain index association on a multidimensional array like this. Any help would be great!
Upvotes: -1
Views: 54
Reputation: 983
A great goto for me:
function sort_multi_array_2_col($arrInbound
, $strColumn1
, $strColumn1Sort = "ASC"
, $strColumn2
, $strColumn2Sort = "ASC") {
reset($arrInbound);
foreach ($arrInbound as $key => $row) {
$columnToSort1[$key] = $row[$strColumn1];
$columnToSort2[$key] = $row[$strColumn2];
}
array_multisort($columnToSort1
, get_sort_flag($strColumn1Sort)
, $columnToSort2
, get_sort_flag($strColumn2Sort)
, $arrInbound);
return $arrInbound;
}
function get_sort_flag($strSort) {
if($strSort == "ASC"){
return SORT_ASC;
} else {
return SORT_DESC;
}
}
Upvotes: 0