PDO: Grouping Associative Arrays by Column Values
Grouping data by specific column values can be useful for organizing and manipulating datasets. This question explores a way to achieve this using PDO's fetchAll method.
The provided example demonstrates a dataset of employees with columns such as name, age, sex, and position. The goal is to obtain an associative array grouped by the name column, resulting in an array structure like:
[ 'Antony' => ['age' => 34, 'sex' => 'M', 'position' => 'programmer'], 'Sally' => ['age' => 30, 'sex' => 'F', 'position' => 'manager'], 'Matthew' => ['age' => 28, 'sex' => 'M', 'position' => 'designer'], ]
The initial approach using PDO::FETCH_GROUP|PDO::FETCH_ASSOC introduces unwanted levels of nesting. To resolve this, the question suggests using a callback function with PDO::FETCH_GROUP|PDO::FETCH_ASSOC|PDO::FETCH_FUNC. However, it encounters issues with the callback function receiving individual elements instead of arrays.
The solution to this issue is to use PDO::FETCH_GROUP|PDO::FETCH_UNIQUE. This approach designates the first column as the array key and sets the remaining columns as values, yielding the desired grouped associative array without unnecessary nesting or array manipulation.
The above is the detailed content of How to Group Associative Arrays by Column Values Using PDO?. For more information, please follow other related articles on the PHP Chinese website!