Skip to content

Instantly share code, notes, and snippets.

@ozin7
Last active July 10, 2020 13:03
Show Gist options
  • Save ozin7/73596aa97344785be80d57d62e0eb342 to your computer and use it in GitHub Desktop.
Save ozin7/73596aa97344785be80d57d62e0eb342 to your computer and use it in GitHub Desktop.
Drupal 9: Sort structured array by the 'weight', 'title', '#weight', '#title'
<?php
use Drupal\Component\Utility\SortArray;
// Sort by `weight`
$exapmle_array = [
['nid' => 21, 'weight' => -10],
['nid' => 3, 'weight' => 10],
['nid' => 1, 'weight' => -100],
];
uasort($data, [SortArray::class, 'sortByWeightElement']);
// Sort by `#weight`
$exapmle_array = [
['#markup' => t('can I'), '#weight' => -10],
['#markup' => t('say'), '#weight' => 10],
['#markup' => t('What'), '#weight' => -100],
];
uasort($data, [SortArray::class, 'sortByWeightProperty']);
// The same methods for the `title`
uasort($data, [SortArray::class, 'sortByTitleElement']);
uasort($data, [SortArray::class, 'sortByTitleProperty']);
@diakivvasyl
Copy link

Cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment