sorting items in an arrays with multiple elements
Posted: Wed Jan 22, 2014 9:39 am
The premise is to have an array with names and associated professions and to sort the array by professions then list out the names.
Lets start with the form that sends an array from some <select> elements
this is sent to be processed and i use this to list out each of the selected items
fairly simple so far. now those options are created from a database which has the option name and a secondary value for each option. Lets say that in the database Mark = Carpenter, John and Peter = Fisherman and Paul = Lawyer i can use this code
this will list out in order as selected the persons name and their occupation.
HOWEVER.. thats not what i want. what i want is a way that in the processed data all im given is the persons names but i want them grouped to their occupation. so if there were 20 names in the database and 4 occupations and ive got 6 <select> elements then when its processed it would list them out with all the carpenters first, then all the fishermen then all the lawyers.
My thought but i cant figure out how to make it work is that in that foreach loop i stick names and related occupations into a new array. then sort that array alphebetically by occupations then do another foreach loop displaying only the names
Lets start with the form that sends an array from some <select> elements
Code: Select all
<select name="d1[]">
<option value="Mark">Mark</option>
<option value="John">John</option>
<option value="Peter">Peter</option>
<option value="Paul">Paul</option>
</select>
<select name="d1[]">
<option value="Mark">Mark</option>
<option value="John">John</option>
<option value="Peter">Peter</option>
<option value="Paul">Paul</option>
</select>
Code: Select all
foreach ($_POST['d1] as $item) {
echo $item."<br>";
}Code: Select all
foreach ($_POST[$group] as $item) {
$result = mysql_query("SELECT * FROM people WHERE peoplename = '$item' ", $connect);//connect to the database here
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$occu = $userData['occupation'];
echo $item." is a ".$occu;
}
HOWEVER.. thats not what i want. what i want is a way that in the processed data all im given is the persons names but i want them grouped to their occupation. so if there were 20 names in the database and 4 occupations and ive got 6 <select> elements then when its processed it would list them out with all the carpenters first, then all the fishermen then all the lawyers.
My thought but i cant figure out how to make it work is that in that foreach loop i stick names and related occupations into a new array. then sort that array alphebetically by occupations then do another foreach loop displaying only the names