很需要php数组的group_by功能,网络上也搜得到写好的函数,但发现codeIgniter4.5新版中已有这个辅助函数,但我用的codeIgniter4.14没有,又不想升级php等一系列东西,就想着把codeIgniter4.5中array_group_by函数复制过来用。
先试着把新版本的array_helper文件及该目录下有个Array子目录一起复制过来,但不行,于是就把这个函数相关的内容复制过来。
这个函数还引用到function arrayAttachIndexedValue,也要复制过来。
以下是添加到array_helper最后的内容
/**
* Recursively attach $row to the $indexes path of values found by
* `dot_array_search()`.
*
* @used-by groupBy()
*/
function arrayAttachIndexedValue(
array $result,
array $row,
array $indexes,
bool $includeEmpty
): array {
if (($index = array_shift($indexes)) === null) {
$result[] = $row;
return $result;
}
$value = dot_array_search($index, $row);
if (! is_scalar($value)) {
$value = '';
}
if (is_bool($value)) {
$value = (int) $value;
}
if (! $includeEmpty && $value === '') {
return $result;
}
if (! array_key_exists($value, $result)) {
$result[$value] = [];
}
$result[$value] = arrayAttachIndexedValue($result[$value], $row, $indexes, $includeEmpty);
return $result;
}
if (! function_exists('array_group_by')) {
/**
* Groups all rows by their index values. Result's depth equals number of indexes
*
* @used-by array_group_by()
*
* @param array $array Data array (i.e. from query result)
* @param array $indexes Indexes to group by. Dot syntax used. Returns $array if empty
* @param bool $includeEmpty If true, null and '' are also added as valid keys to group
*
* @return array Result array where rows are grouped together by indexes values.
*/
function array_group_by(array $array, array $indexes, bool $includeEmpty = false): array
{
if ($indexes === []) {
return $array;
}
$result = [];
foreach ($array as $row) {
$result = arrayAttachIndexedValue($result, $row, $indexes, $includeEmpty);
}
return $result;
}
}