WC_Tracker::extract_group_key()private staticWC 1.0

Extract the group key for an associative array of objects which have unique ids in the key. A 'group_key' property is introduced in the object. For example, two objects with keys like 'WooDataPay #123' and 'WooDataPay #78' would both have a group_key of 'WooDataPay **' after this function call.

Метод класса: WC_Tracker{}

Хуков нет.

Возвращает

Массив. Contains the objects with a group_key property.

Использование

$result = WC_Tracker::extract_group_key( $objects, $default_key );
$objects(массив) (обязательный)
The array of objects that need to be grouped.
$default_key(строка) (обязательный)
The property that will be the default group_key.

Код WC_Tracker::extract_group_key() WC 8.1.1

private static function extract_group_key( $objects, $default_key ) {
	$keys = array_keys( $objects );

	// Sort keys by length and then by characters within the same length keys.
	usort(
		$keys,
		function( $a, $b ) {
			if ( strlen( $a ) === strlen( $b ) ) {
				return strcmp( $a, $b );
			}
			return ( strlen( $a ) < strlen( $b ) ) ? -1 : 1;
		}
	);

	// Look for common tokens in every pair of adjacent keys.
	$prev = '';
	foreach ( $keys as $key ) {
		if ( $prev ) {
			$comm_tokens = array();

			// Tokenize the current and previous gateway names.
			$curr_tokens = preg_split( '/[ :,\-_]+/', $key );
			$prev_tokens = preg_split( '/[ :,\-_]+/', $prev );

			$len_curr = count( $curr_tokens );
			$len_prev = count( $prev_tokens );

			$index_unique = -1;
			// Gather the common tokens.
			// Let us allow for the unique reference id to be anywhere in the name.
			for ( $i = 0; $i < $len_curr && $i < $len_prev; $i++ ) {
				if ( $curr_tokens[ $i ] === $prev_tokens[ $i ] ) {
					$comm_tokens[] = $curr_tokens[ $i ];
				} elseif ( preg_match( '/\d/', $curr_tokens[ $i ] ) && preg_match( '/\d/', $prev_tokens[ $i ] ) ) {
					$index_unique = $i;
				}
			}

			// If only one token is different, and those tokens contain digits, then that could be the unique id.
			if ( count( $curr_tokens ) - count( $comm_tokens ) <= 1 && count( $comm_tokens ) > 0 && $index_unique > -1 ) {
				$objects[ $key ]->group_key  = implode( ' ', $comm_tokens );
				$objects[ $prev ]->group_key = implode( ' ', $comm_tokens );
			} else {
				$objects[ $key ]->group_key = $objects[ $key ]->$default_key;
			}
		} else {
			$objects[ $key ]->group_key = $objects[ $key ]->$default_key;
		}
		$prev = $key;
	}
	return $objects;
}