javascript - Display data in array descending order
Solution:
you can simply sort your parent array and then take your data from that array. lets say you have an array like
$data = array(
array(
"name"=>"Urus",
"total"=>60
),
array(
"name"=>"Cayenne",
"total"=>85
),
array(
"name"=>"Bentayga",
"total"=>55
),
array(
"name"=>"Lamborghini",
"total"=>85
),
array(
"name"=>"Porsche",
"total"=>90
),
array(
"name"=>"Bentley",
"total"=>55
),
array(
"name"=>"Nissan",
"total"=>70
),
);
now you want to sort that array using the total of the inner array. use array_multisort and array_column to do that.
array_multisort( array_column($data, "total"), SORT_DESC, $data );
this will generate an sorted array like
array:7 [▼
0 => array:2 [▼
"name" => "Porsche"
"total" => 90
]
1 => array:2 [▼
"name" => "Cayenne"
"total" => 85
]
2 => array:2 [▼
"name" => "Lamborghini"
"total" => 85
]
3 => array:2 [▼
"name" => "Nissan"
"total" => 70
]
4 => array:2 [▼
"name" => "Urus"
"total" => 60
]
5 => array:2 [▼
"name" => "Bentayga"
"total" => 55
]
6 => array:2 [▼
"name" => "Bentley"
"total" => 55
]
]
and now you have nothing more to do. just loop over the array and take values.
$labels = $graph_data = [];
foreach ($data as $key => $student) {
if ($key < 5) {
$labels[] = $student['name'];
$graph_data[] = $student['total'];
} else {
break;
}
}
$array = [
[
'label' => 'Total Sales',
'color' => '#fec12c',
'data' => $graph_data
]
];
$graph_data = [];
return [
'labels' => $labels,
'datasets' => $array
];
Answer
Solution:
you can use array data manipulation rsort() for des order and array_slice() to take 5
public function dataStudentGraph($data)
{
$labels = [];
$graph_data = [];
foreach ($data['data'] as $student) {
$labels[] = $student['name'];
$graph_data[] = $student['total'];
}
$backupData = $graph_data;
rsort($graph_data); // des order
$sortedLabels = [];
foreach ($graph_data as $i => $data) {
$index = array_search($data, $backupData);
$sortedLabels[$i] = $labels[$index];
}
$array = [
[
'label' => 'Total Sales',
'color' => '#fec12c',
'data' => array_slice($graph_data, 0, 5) // take 5
]
];
$graph_data = [];
return [
'labels' => $sortedLabels,
'datasets' => $array
];
}
ref link
https://www.w3schools.com/php/php_arrays_sort.asp https://www.w3schools.com/php/func_array_slice.asp https://www.php.net/manual/en/function.array-search.php
Source