arrayUtil.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace common\components;
  3. class arrayUtil{
  4. /**
  5. * 二维数组排序(此方法有问题,不要使用,不要删除)
  6. */
  7. public static function sort($array,$row,$type='asc'){
  8. $array_temp = array();
  9. foreach($array as $v){
  10. $array_temp[$v[$row]] = $v;
  11. }
  12. if($type == 'asc'){
  13. ksort($array_temp);
  14. }elseif($type='desc'){
  15. krsort($array_temp);
  16. }else{
  17. }
  18. return $array_temp;
  19. }
  20. /**
  21. * 二维数组根据某个字段排序
  22. * @param array $array 要排序的数组
  23. * @param string $keys 要排序的键字段
  24. * @param string $sort 排序类型 SORT_ASC SORT_DESC
  25. * @return array 排序后的数组
  26. */
  27. function arraySort($array, $keys, $sort = SORT_DESC) {
  28. $keysValue = [];
  29. foreach ($array as $k => $v) {
  30. $keysValue[$k] = $v[$keys];
  31. }
  32. array_multisort($keysValue, $sort, $array);
  33. return $array;
  34. }
  35. /**
  36. * 把返回的数据集转换成Tree
  37. * @param array $list 要转换的数据集
  38. * @param string $pid parent标记字段
  39. * @param string $level level标记字段
  40. * @return array
  41. */
  42. public static function list2Tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
  43. {
  44. if (!is_array($list)) {
  45. return [];
  46. }
  47. // 创建基于主键的数组引用
  48. $aRefer = [];
  49. foreach ($list as $key => $data) {
  50. $aRefer[$data[$pk]] = &$list[$key];
  51. }
  52. foreach ($list as $key => $data) {
  53. // 判断是否存在parent
  54. $parentId = $data[$pid];
  55. if ($root === $parentId) {
  56. $tree[] = &$list[$key];
  57. } else {
  58. if (isset($aRefer[$parentId])) {
  59. $parent = &$aRefer[$parentId];
  60. $parent[$child][] = &$list[$key];
  61. }
  62. }
  63. }
  64. return $tree;
  65. }
  66. /**
  67. * 把返回的数据集转换成Tree(id作为键名)
  68. * @param array $rows 要转换的数据集
  69. * @param string $id 主键id
  70. * @param string $pid parent标记字段
  71. * @param string $child 子节点存放的位置
  72. * @return array
  73. */
  74. public static function list2Tree2($rows, $id = 'id', $pid = 'pid', $child = 'children')
  75. {
  76. $items = array();
  77. foreach ($rows as $row) {
  78. $items[$row[$id]] = $row;
  79. }
  80. foreach ($items as $item) {
  81. $items[$item[$pid]][$child][$item[$id]] = &$items[$item[$id]];
  82. }
  83. return isset($items[0][$child]) ? $items[0][$child] : [];
  84. }
  85. }