Ordering multi word tags by second value


Is it possible to order a collection of multi-word tags, say in alphabetical order from A to Z, using the second value as key?

In my case it would be a tag composed by firstname lastname, that I’d like to print in the order firstname lastname, but ordering by lastname.


You didn’t share the data you have so I’m assuming tag is a simple text field. You may need to adjust it to match your data…

$pages = $pages->map(function($page) {
  // convert tag name to array
  $tag = explode(' ', $page->tag()->value());

  // take last item of the array
  $page->lastname = array_pop($tag);

  return $page;


So this is basically adding a new field to each item in the collection so that you can sort it by the new field.

If it’s just an array of plucked values, you can use array_map():

    $tags = page('projects')->children()->pluck('tags', ',', true);

    $callback = function($item) {
      $tag = explode(' ', $item);
      return array_reverse($tag);

    $map = array_map($callback, $tags);

    array_multisort($map, SORT_ASC);

    foreach($map as $key => $name) {
      echo $name[1] . ' ' . $name[0];
1 Like

Thanks, works like a charm.