This is an old revision of the document!
PHP RFC: array_column results grouping
- Version: 1.0
- Date: 2021-11-28
- Author: Hassan Ahmed, 7snovic@gmail.com
- Status: Draft
- First Published at: https://wiki.php.net/rfc/array_column_results_grouping
Introduction
array_column ignores the duplicated rows for each similar columnt/index. The Purpose of the RFC is to add a new parameter to allow array_column to group the similar entries.
Proposal
This RFC is adding a new boolean parameter to array_column to determine it's behaviour of grouping or not.
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null, $grouping = null): array
Or we can implement it as a new function with something like
array_column_group(array $array, int|string|null $column_key, int|string|null $index_key = null)
And keep the same parameters.
The current behavior is when you have multiple elements share the same key, it will be overwritten. let's assume that we have the following.
<?php $array = [ ['id' => 1, 'name' => 'hassan'], ['id' => 2, 'name' => 'sara'], ['id' => 3, 'name' => 'selim'], ['id' => 4, 'name' => 'chris'], ['id' => 5, 'name' => 'sara'], ];
when we use array_column with this the output will be
print_r(array_column($array, null, 'name')); Array ( [hassan] => Array ( [id] => 1 [name] => hassan ) [sara] => Array ( [id] => 5 [name] => sara ) [selim] => Array ( [id] => 3 [name] => selim ) [chris] => Array ( [id] => 4 [name] => chris ) )
The RFC implements a fourth parameter to array_column to group the results in an indexed array to group all the similar elements, so we can use :
print_r(array_column($array, null, 'name', true)); Array ( [hassan] => Array ( [0] => Array ( [id] => 1 [name] => hassan ) ) [sara] => Array ( [0] => Array ( [id] => 2 [name] => sara ) [1] => Array ( [id] => 5 [name] => sara ) ) [selim] => Array ( [0] => Array ( [id] => 3 [name] => selim ) ) [chris] => Array ( [0] => Array ( [id] => 4 [name] => chris ) ) )
Backward Incompatible Changes
No backward incompatible breaks.
Proposed PHP Version(s)
Next PHP 8.x, currently PHP 8.2.
RFC Impact
To Existing Extensions
Standard ext
Proposed Voting Choices
Yes/No vote.