I have a list of (xml) items, each item has a category and a name:
1 | Joe
2 | Carol
3 | Bruce
1 | Michael
1 | Alan
2 | Brian
I want to sort the names ascending within categories descending like so:
3 | Bruce
2 | Brian
2 | Carol
1 | Alan
1 | Joe
1 | Michael
with the aim of creating a Select dropdown on a web page with each category as an OptGroup and the names sorted within the OptGroup. I have very little experience with PHP, I think I need to sort merge arrays, but after many hours trying to understand how to, I'm not making much progress. Any help greatly appreciated
$name = array("Joe", "Carol", "Bruce", "Michael","Alan","Brian");
sort($name);
php-in built function sort will produce desire result
$data[] = array('category' => 1, 'name' => 'Joe');
$data[] = array('category' => 2, 'name' => 'Carol');
$data[] = array('category' => 3, 'name' => 'Bruce');
$data[] = array('category' => 1, 'name' => 'Michael');
$data[] = array('category' => 1, 'name' => 'Alan');
$data[] = array('category' => 2, 'name' => 'Brian');
<?php
// Obtain a list of columns
$category =array();
$name =array();
foreach ($data as $key => $row) {
$category[$key] = $row['category'];
$name[$key] = $row['name'];
}
// Sort the data with category descending, name ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($category, SORT_DESC, $name, SORT_ASC, $data);
echo '<pre>'; print_r($category);
?>
Hi thanks to everybody for your help including all the other Stackoverflow questions which I googled to piece this together, not sure how I did it, bit of a case of an infinite number of monkeys or should that be newbies, anways here's what worked for me. Sorts names ascending within contributions descending
function compare($a, $b) {
if ($a['contribution'] == $b['contribution']) {
return ($a['name'] < $b['name']) ? -1 : 1;
} else {
return ($b['contribution'] - $a['contribution']);
}
}
usort($ads_by_cotribution, 'compare');
It's all magic to me, that's the beauty of it. I didn't include the case of names being equal 'cause there shouldn't be any and as I understand equal values would still stay together just in a different order. I'd like to understand how these functions work, do they continuously walk through the array until there's no change in the order - what we used to call a bubble sort? Does ($b['contribution'] - $a['contribution']) indicate which is the larger? Finley is there a difference between sorting contributions - a numeric field and names - an alpha field?