How can I sort the array ["Name":"OVERALL"]
always last in the array element. This array ["Name":"OVERALL"]
always on index 1. I think my current method is not a really good implementation. Is there any better ways?
[
["Name":"AHMAD SUFFIAN BIN AHMAD LOTFI","SLAData":[0,0,0,0,0,0],"RatingData":[0,0,0,0,0,0]],
["Name":"OVERALL","SLAData":[19,8,50,0,0,100],"RatingData":[95,95,100,0,0,0]],
["Name":"JAYALETCHUMI A\/P VENGADASALAM","SLAData":[33,14,100,0,0,0],"RatingData":[90,90,100,0,0,0]],
["Name":"MOHAMMAD FIRDHAUS BIN ISMAIL","SLAData":[0,0,0,0,0,0],"RatingData":[100,100,0,0,0,0]],
["Name":"YOGESWARAN A\/L PUSSAN","SLAData":[0,0,0,0,0,0],"RatingData":[0,0,0,0,0,0]],
["Name":"JAYAKUMAR PARAMASIVAM","SLAData":[0,0,0,0,0,100],"RatingData":[0,0,0,0,0,0]]
]
This is my current method
$Temp=[];
$output = array_slice($MonthlyData, 1, 1);
foreach ($MonthlyData as $data) {
if($data['Name']!='OVERALL')
$Temp[] = $data;
}
}
$Temp[] = $output;
$MonthlyData = $Temp;
There's multiple ways to do this. I chose a way that doesn't require changing the code you provided much. All this code does is add the elements to a front of a temprary array unless it is the one you want to be last. That one it puts on the end of the array.
$MonthlyData = [
["Name" => "AHMAD SUFFIAN BIN AHMAD LOTFI","SLAData" => [0,0,0,0,0,0],"RatingData" => [0,0,0,0,0,0]],
["Name" => "OVERALL","SLAData" => [19,8,50,0,0,100],"RatingData" => [95,95,100,0,0,0]],
["Name" => "JAYALETCHUMI A\/P VENGADASALAM","SLAData" => [33,14,100,0,0,0],"RatingData" => [90,90,100,0,0,0]],
["Name" => "MOHAMMAD FIRDHAUS BIN ISMAIL","SLAData" => [0,0,0,0,0,0],"RatingData" => [100,100,0,0,0,0]],
["Name" => "YOGESWARAN A\/L PUSSAN","SLAData" => [0,0,0,0,0,0],"RatingData" => [0,0,0,0,0,0]],
["Name" => "JAYAKUMAR PARAMASIVAM","SLAData" => [0,0,0,0,0,100],"RatingData" => [0,0,0,0,0,0]]
];
$Temp=[];
foreach ($MonthlyData as $data) {
if ($data['Name'] === 'OVERALL') {
$Temp[] = $data;
}
else {
array_unshift($Temp, $data);
}
}
$MonthlyData = $Temp;
If you want a more concise way to do it, use usort()
to sort based on a specified criteria. In this case, always put an array last if it's "name" value is "OVERALL".
usort($MonthlyData, static function ($a, $b) {
return ($a['Name'] === 'OVERALL') ? 1 : -1;
});