dougblitz210 dougblitz210 - 1 year ago 74
PHP Question

print a header and sort by an array value

I have an array containing possible values:

$auto_types = array(CHEVY, FORD, DODGE);

And I have have arrays that contain those values:

$my_cars = array(
array("make" => "FORD", model => "Thunderbird", "year" => 1983),
array("make" => "FORD", model => "Mustang", "year" => 1971),
array("make" => "CHEVY", model => "Impala", "year" => 1995),
array("make" => "DODGE", model => "Charger", "year" => 2015),
array("make" => "CHEVY", model => "Corvette", "year" => 2011),
array("make" => "CHEVY", model => "Camaro", "year" => 2012)

I want to return a list that supplies a header of each make, and then sorts each car by the Make. So the output would be:


1995 Impala

2012 Corvette

2011 Camaro


2015 Charger


1971 Mustang

1983 Thunderbird

I know I can run a
loop and sort by make, but the key here is that I want a header for each make, instead of listing it for every car.
Anyone have a good way to do this? -- Not sure if the first array is even needed, but it seemed like a good idea to create it at the time.

Answer Source

First you'll want to sort the array by make. You can do that with the help of array_multisort().

When you loop through your array for your list output, you can keep a variable that stores the make of the previous car. Then, whenever there's a new make, just print a header before the car's entry.

$ex_make = '';

foreach($my_cars as $car) {
    if ($car['make'] != $ex_make) {
    $ex_make = $car['make'];

You can make your life easier by grouping your cars by make into a multidimensional array. It'll spare you from the sorting process (and the grouping loops suggested in other answers). If you have lots more cars coming in, you'll want to consider using a database instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download