arrayUtil.php 2.3 KB

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