bp_sort_by_key( array $items, string|int $key, string $type = 'alpha', bool $preserve_keys = false )

Sort an array of objects or arrays by a specific key/property.

Description

The main purpose for this function is so that you can avoid having to create your own awkward callback function for usort().

Parameters

$items

(Required) The items to be sorted. Its constituent items can be either associative arrays or objects.

$key

(Required) The array index or property name to sort by.

$type

(Optional) Sort type. 'alpha' for alphabetical, 'num' for numeric. Default: 'alpha'.

Default value: 'alpha'

$preserve_keys

(Optional) Whether to keep the keys or not.

Default value: false

Return

(array) $items The sorted array.

Source

File: bp-core/bp-core-functions.php

function bp_sort_by_key( $items, $key, $type = 'alpha', $preserve_keys = false ) {
	$callback = function( $a, $b ) use ( $key, $type ) {
		$values = array( 0 => false, 1 => false );
		foreach ( func_get_args() as $indexi => $index ) {
			if ( isset( $index->{$key} ) ) {
				$values[ $indexi ] = $index->{$key};
			} elseif ( isset( $index[ $key ] ) ) {
				$values[ $indexi ] = $index[ $key ];
			}
		}

		if ( isset( $values[0], $values[1] ) ) {
			if ( 'num' === $type ) {
				$cmp = $values[0] - $values[1];
			} else {
				$cmp = strcmp( $values[0], $values[1] );
			}

			if ( 0 > $cmp ) {
				$retval = -1;
			} elseif ( 0 < $cmp ) {
				$retval = 1;
			} else {
				$retval = 0;
			}
			return $retval;
		} else {
			return 0;
		}
	};

	if ( true === $preserve_keys ) {
		uasort( $items, $callback );
	} else {
		usort( $items, $callback );
	}

	return $items;
}

Changelog

Changelog
Version Description
BuddyPress 2.7.0 Added $preserve_keys parameter. BuddyPress 2.7.0 Added $preserve_keys parameter.
BuddyPress 2.2.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.