I know this is a bit outdated, I'm sorry, but I did this with an array of objects. I wanted to display the title of each object on the page with the alphabet. I used the following:
$items = array ( [0] => stdClass Object ( [title] => Alpha [name] => Joe Blogs [address] => 123 Harry Street ) [1] => stdClass Object ( [title] => Bravo [name] => Jane Doe [address] => 456 Upton Street ) [2] => stdClass Object ( [title] => Charlie [name] => Jane Doe [address] => 456 Upton Street ) )
This function is then declared in a helper class.
public static function alphaSortItems ($items) { $sortedItems = array(); foreach ($items as $item) { $sortedItems[$item->title[0]][] = $item; } return $sortedItems; }
Then, to display them, I used
<?php $sortedItems = Helper::alphaSortItems($this->items); ?> <?php foreach ($sortedItems as $key => $value) : ?> <h2><?php echo $key; ?></h2> <?php foreach ($value as $item) : ?> <h3><?php echo $item->title; ?></h3> <?php endforeach; ?> <?php endforeach; ?>
That I did it anyway :-)
source share