PHP's array key grouping is a powerful feature that allows you to classify arrays based on custom rules. This technique is widely used in data aggregation, data filtering, and data transformation. Common use cases include:
PHP provides several built-in functions to group arrays by key:
Example 1: Group Orders by User ID
In this example, we group a list of orders based on the user ID:
$orders = [
['user_id' => 1, 'product_id' => 1, 'quantity' => 2],
['user_id' => 1, 'product_id' => 2, 'quantity' => 3],
['user_id' => 2, 'product_id' => 3, 'quantity' => 1],
];
$groupedOrders = array_group_by($orders, 'user_id');
After executing, $groupedOrders will be a multi-dimensional array grouped by user ID:
[
1 => [
['user_id' => 1, 'product_id' => 1, 'quantity' => 2],
['user_id' => 1, 'product_id' => 2, 'quantity' => 3],
],
2 => [
['user_id' => 2, 'product_id' => 3, 'quantity' => 1],
],
]
Example 2: Filter Keys with a Specific Suffix
In this example, we filter all settings with a .site suffix:
$settings = [
'site.title' => 'My Site',
'site.description' => 'A great website',
'user.name' => 'John Doe',
];
$filteredSettings = array_filter($settings, function($key) {
return strpos($key, '.site') !== false;
});
After executing, $filteredSettings will only contain keys with the .site suffix:
[
'site.title' => 'My Site',
'site.description' => 'A great website',
]
By effectively using PHP's array key grouping functions, you can efficiently organize and manage array data. These functions offer flexibility in aggregating, filtering, and transforming data, helping developers handle complex data structures with ease.