WC_Tracker::extract_group_key
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.
Method of the class: WC_Tracker{}
No Hooks.
Returns
Array. Contains the objects with a group_key property.
Usage
$result = WC_Tracker::extract_group_key( $objects, $default_key );
- $objects(array) (required)
- The array of objects that need to be grouped.
- $default_key(string) (required)
- The property that will be the default group_key.
WC_Tracker::extract_group_key() WC Tracker::extract group key code WC 10.4.3
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 = is_array( $curr_tokens ) ? count( $curr_tokens ) : 0;
$len_prev = is_array( $prev_tokens ) ? count( $prev_tokens ) : 0;
$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 ( $len_curr - 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;
}