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 Description

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


Parameters 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


Top ↑

Return Return

(array) $items The sorted array.


Top ↑

Source 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;
}

Top ↑

Changelog Changelog

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

Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.