复制CodeIgniter新版的array_group_by辅助函数
创始人
2024-11-13 04:35:22

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

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...