| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace common\components;
- class arrayUtil
- {
-
- //二维数组排序(此方法有问题,不要使用,不要删除)
- public static function sort($array, $row, $type = 'asc')
- {
- $array_temp = array();
- foreach ($array as $v) {
- $array_temp[$v[$row]] = $v;
- }
- if ($type == 'asc') {
- ksort($array_temp);
- } elseif ($type = 'desc') {
- krsort($array_temp);
- } else {
- }
- return $array_temp;
- }
-
- //二维数组根据某个字段排序 $key键名
- public static function arraySort($array, $key, $sort = SORT_DESC)
- {
- $data = [];
- foreach ($array as $k => $v) {
- $data[$k] = $v[$key];
- }
- array_multisort($data, $sort, $array);
- return $array;
- }
-
- /**
- * 把返回的数据集转换成Tree
- * @param array $list 要转换的数据集
- * @param string $pid parent标记字段
- * @param string $level level标记字段
- * @return array
- */
- public static function list2Tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
- {
- if (!is_array($list)) {
- return [];
- }
- // 创建基于主键的数组引用
- $aRefer = [];
- foreach ($list as $key => $data) {
- $aRefer[$data[$pk]] = &$list[$key];
- }
- foreach ($list as $key => $data) {
- // 判断是否存在parent
- $parentId = $data[$pid];
- if ($root === $parentId) {
- $tree[] = &$list[$key];
- } else {
- if (isset($aRefer[$parentId])) {
- $parent = &$aRefer[$parentId];
- $parent[$child][] = &$list[$key];
- }
- }
- }
- return $tree;
- }
-
- /**
- * 把返回的数据集转换成Tree(id作为键名)
- * @param array $rows 要转换的数据集
- * @param string $id 主键id
- * @param string $pid parent标记字段
- * @param string $child 子节点存放的位置
- * @return array
- */
- public static function list2Tree2($rows, $id = 'id', $pid = 'pid', $child = 'children')
- {
- $items = array();
- foreach ($rows as $row) {
- $items[$row[$id]] = $row;
- }
- foreach ($items as $item) {
- $items[$item[$pid]][$child][$item[$id]] = &$items[$item[$id]];
- }
- return isset($items[0][$child]) ? $items[0][$child] : [];
- }
-
- }
|