您的位置:首页 > 科技 > IT业 > 复制CodeIgniter新版的array_group_by辅助函数

复制CodeIgniter新版的array_group_by辅助函数

2025/3/28 5:47:01 来源:https://blog.csdn.net/stone5/article/details/140866614  浏览:    关键词:复制CodeIgniter新版的array_group_by辅助函数

很需要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;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com