Pulling certain structure items and organising them

Hi all,

Just wondering what would be the best way to sort structure field items by one of the structure item fields? Is it possible to group them?

What I have is a service with different plans, so there are different features depending on which plan you pay for.

This seems to do what I need it to, anyone have any improvements I can make? Not sure if it’s the best way…

  <?php $features = $page->features()->toStructure() ?>
  <?php $standardFeatures = $features->filterBy('featurePlan', '==', 'standard'); ?>
  <?php $premiumFeatures = $features->filterBy('featurePlan', '==', 'premium'); ?>
  <?php foreach ($standardFeatures as $standardFeature) : ?>
    <?= $standardFeature->featurePlan() ?>">
    <?php if($standardFeature->featureTitle()->isNotEmpty()): ?>
      <?= $standardFeature->featureTitle() ?>
    <?php endif ?>
    <?php if($standardFeature->featureDescription()->isNotEmpty()): ?>
      <?= $standardFeature->featureDescription() ?>
    <?php endif ?>
  <?php endforeach ?>
  <?php foreach ($premiumFeatures as $premiumFeature) : ?>
    <?= $premiumFeature->featurePlan() ?>">
    <?php if($premiumFeature->featureTitle()->isNotEmpty()): ?>
      <?= $premiumFeature->featureTitle() ?>
    <?php endif ?>
    <?php if($premiumFeature->featureDescription()->isNotEmpty()): ?>
      <?= $premiumFeature->featureDescription() ?>
    <?php endif ?>
  <?php endforeach ?>

You can use groupBy() instead:

Thanks @texnixe, I’ll have a look at that. Do you know why it would be better? Would it be more or less the same code but just switch filterBy with groupBy?

Well, your filtering is done manually, so in case you later want to add another plan or so, you would have to touch your logic. With groupBy(), you are more flexible without having to touch your code once there are more plans.

And in general, your code would be shorter and not as repetitive. This will be even more obvious, once you add some HTML.

I see, thanks very much. I was hoping for some feedback like this. Much appreciated!