1

My problem is that I don't know/understand how to sort complex arrays.

I have a multi dimensional array of users from an external API. So it's not an array that I fetch from the Craft database. Let's call this array the "Main Array".

The Main Array contains multiple users, every user has multiple fields such as firstname, lastname, department, and so on. So every user in the Main Array is actually another array that we shall call a User Array. So the Main Array consists of multiple User arrays which consists of multiple fields.

First I group the Main array by the department field of a user (using the Twig group filter). So far so good, that way I can list all my users in department blocks.

But within those blocks, I want them to be alphabetically sorted by their lastname. So I need a way to let Craft know to sort my User Arrays by the lastname field of a user within the Main Array.

Seems logical and simple, but I can't figure out how. I tried SuperSort, but the standard asort function won't work. I than tried superSort('SortAs', '{lastnameField}') but that didn't work either.

2

Not really an answer that fixes the question per sé if anyone else has the same issue, but none the less the answer that worked for me was simple:

Split up your sorting where possible and simplify things!

I wanted my main array to be sorted by condition A, grouped by condition B and than sort the sub arrays alphabeticaly. All done to the same array in a few lines of code so I could use this one array in my template to get all information from it. Bad idea.

So what I did was sort everything by condition A in PhP in my plugin, in my template I than group everything by condition B and only when I needed to iterate over my array to reveal my sub arrays, only then I sort the values alphabetically.

So short answer: keep it simple damnit! :)

1

It's a bit hard to help as you didn't provide any code. But I suggest to apply the supersort filter before grouping by the department property.

{% set usersSorted = users|supersort('sortAs', '{{ object.lastname }}') %}
{% set usersGrouped = usersSorted|group('department') %}
  • Alright, got it working. I had to re-arrange some sorting. I tried to sort a multi-dimensional array in a very complex way and by splitting things up and sorting them when needed, I got things working. Sorting before grouping was not really an option though. Thanks anyway for helping! – Tom De Smet Dec 14 '15 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.