The input should be either multidimensional array or an array of objects.
The $key can be either a key name of the sub-array, a property name of object, or an anonymous
function that must return the value that will be used as a key.
$groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
on keys specified.
If the $key is specified as null or a value of an element corresponding to the key is null in addition
to $groups not specified then the element is discarded.
For example:
php
$array = [
['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
['id' => '345', 'data' => 'def', 'device' => 'tablet'],
['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
$result = ArrayHelper::index($array, 'id');
The result will be an associative array, where the key is the value of id attribute
php
[
'123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
'345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
The second element of an original array is overwritten by the last element because of the same id
]
An anonymous function can be used in the grouping array as well.
php
$result = ArrayHelper::index($array, function ($element) {
return $element['id'];
});
Passing id as a third argument will group $array by id:
php
$result = ArrayHelper::index($array, null, 'id');
The result will be a multidimensional array grouped by id on the first level, by device on the second level
and indexed by data on the third level:
php
[
'123' => [
['id' => '123', 'data' => 'abc', 'device' => 'laptop']
],
'345' => [ // all elements with this index are present in the result array
['id' => '345', 'data' => 'def', 'device' => 'tablet'],
['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
]
]
The anonymous function can be used in the array of grouping keys as well:
php
$result = ArrayHelper::index($array, 'data', [function ($element) {
return $element['id'];
}, 'device']);
The result will be a multidimensional array grouped by id on the first level, by the device on the second one
and indexed by the data on the third level:
php
[
'123' => [
'laptop' => [
'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
]
],
'345' => [
'tablet' => [
'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
],
'smartphone' => [
'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
]
]
]