I wish to create a list of items from an array, grouped by a value within that array.
Take this array:
$people = array(
0 => array(
"Forename" => "Jim",
"Surname" => "Smith"
),
1 => array(
"Forename" => "Mike",
"Surname" => "Johnson"
),
2 => array(
"Forename" => "Kim",
"Surname" => "Smith"
),
3 => array(
"Forename" => "Paul",
"Surname" => "Jones"
)
);
Specifically I'd like to run a foreach
on $people
, grouping them by unique surname. i.e. the desired output would be:
<select>
<optgroup label="Smith">
<option>Jim</option>
<option>Kim</option>
</optgroup>
<optgroup label="Johnson">
<option>Mike</option>
</optgroup>
<optgroup label="Jones">
<option>Paul</option>
</optgroup>
</select>
I'm struggling to come up with anything vaguely efficient and the Google gods aren't watching over me today :( What's the best approach for such a use-case in PHP?