Base material :
I have a base list $food
:
[{"id":"123","name":"apple"},{"id":"456","name":"Rost Beef"},...]
that i first reduce with $food_reduced = array_count_values(array_columns($food, "id"));
.
[{123:2},{456:5},...]
Then i loop through $food_reduced
with foreach($food_reduced as $id => $count)
to query a DataBase to get the category (vegetables, fruits, meat, fish, etc..) that i store into $food_byCategory = array();
declared right before the loop :
if ($food_byCategory[$row["ctg_name"]])
{
$food_byCategory[$row["ctg_name"]] += $count;
}
else
{
$food_byCategory[$row["ctg_name"]] = $count;
}
Which gives me this array that I want to sort (gettype() says it's an Array at least) in PHP :
{
Vegetable: 2
Fruit: 1
Fish: 5
Drinks: 1
Meat: 2
Desert: 3
}
to this :
{
Fish: 5
Desert: 3
Meat: 2
Vegetable: 2
Drinks: 1
Fruit: 1
}
Notice the sorting by key
once the sorting by value
is done.
The goal is then to display this list into an html list by value descending.
I have tried asort
, sort
, arsort
, with or without the option SORT_NUMERIC
etc...
Wether it's not working at all or it's erasing the keys and replacing them with indexes.
I've also tried typecasting it into an array, but nothing changed (probably because it is an Array already ? But yet, not an Object ?)
I'm kinda lost. Help ?
SOLVED my issue by building the "count" array another way :
if (!in_array($ctg_id, array_column($food_byCategory, "id")))
{
$food_byCategory[] = array(
"id" => $ctg_id,
"count" => 1
);
}
else
{
$index = array_search($ctg_id, array_column($food_byCategory, "id"));
$food_byCategory[$index]["count"]++;
}
and then sorting it with usort
:
usort($food_byCategory, function($a, $b) {
return $b["count"] <=> $a["count"];
});