Automattic\WooCommerce\Utilities
ArrayUtil::group_by_column()
Given an array of associative arrays, all having a shared key name ("column"), generates a new array in which keys are the distinct column values found, and values are arrays with all the matches found (or only the last matching array found, if $single_values is true). See ArrayUtilTest for examples.
Method of the class: ArrayUtil{}
No Hooks.
Return
Array
. The grouped array.
Usage
$result = ArrayUtil::group_by_column( $items, $column, $single_values ): array;
- $items(array) (required)
- The array to process.
- $column(string) (required)
- The name of the key to group by.
- $single_values(true|false)
- True to only return the last suitable array found for each column value.
Default: false
ArrayUtil::group_by_column() ArrayUtil::group by column code WC 9.3.3
public static function group_by_column( array $items, string $column, bool $single_values = false ): array { if ( $single_values ) { return array_combine( array_column( $items, $column ), array_values( $items ) ); } $distinct_column_values = array_unique( array_column( $items, $column ), SORT_REGULAR ); $result = array_fill_keys( $distinct_column_values, array() ); foreach ( $items as $value ) { $result[ $value[ $column ] ][] = $value; } return $result; }