How to sort acf repeater field using subfield

Recently I needed to sort list of documents which I have recorded using a acf repeater field

the list of documents need to be shown in alphabetical order. After completion it looks like below.

Document list sorted alphabetically

Attachments is a ACF Repeater field. It has two subfields, label and filename. we will sort the list using filename.

ACF Config
<?php $attachmentRepeater = get_field('attachments'); ?>
<?php if (count($attachmentRepeater) > 0) : ?>
	<h3>Downloads</h3>
	<?php $upload_dir = wp_upload_dir();
	$names = array_filter($attachmentRepeater, fn ($elm) => $elm['filename']);
	array_multisort($names, SORT_ASC, $attachmentRepeater);

	foreach ($attachmentRepeater as $attachment) : ?>
		<!-- html content -->
	<?php endforeach; ?>
<?php endif; ?>

Here we get the acf repeater field using get_field . which will return us an Array.

We check the count before showing the element. When the count is 0 we aren’t rendering the Block.

Using php array_filter methods we can get an array of file names.

Then we use array_multisort to sort original array. this will sort original array to the order of $names using the common key ‘filename’

That’s it. Then we can loop over sorted array and generate HTML content as desired.