helpers.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. if (!function_exists('make_tree')) {
  3. /**
  4. * @param array $list
  5. * @param int $parentId
  6. * @return array
  7. */
  8. function make_tree(array $list, $parentId = 0)
  9. {
  10. $tree = [];
  11. if (empty($list)) {
  12. return $tree;
  13. }
  14. $newList = [];
  15. foreach ($list as $k => $v) {
  16. $newList[$v['id']] = $v;
  17. }
  18. foreach ($newList as $value) {
  19. if ($parentId == $value['parent_id']) {
  20. $tree[] = &$newList[$value['id']];
  21. } elseif (isset($newList[$value['parent_id']])) {
  22. $newList[$value['parent_id']]['children'][] = &$newList[$value['id']];
  23. }
  24. }
  25. return $tree;
  26. }
  27. }
  28. if (!function_exists('text_diff')) {
  29. function text_diff(string $text1, string $text2): string
  30. {
  31. $text1 = str_replace('&nbsp;', '', trim($text1));
  32. $text2 = str_replace('&nbsp;', '', trim($text2));
  33. $w = explode("\n", $text1);
  34. $o = explode("\n", $text2);
  35. $w1 = array_diff_assoc($w, $o);
  36. $o1 = array_diff_assoc($o, $w);
  37. $w2 = array();
  38. $o2 = array();
  39. foreach ($w1 as $idx => $val)
  40. $w2[sprintf("%03d<", $idx)] = sprintf("%03d- ", $idx + 1) . "<del>" . trim($val) . "</del>";
  41. foreach ($o1 as $idx => $val)
  42. $o2[sprintf("%03d>", $idx)] = sprintf("%03d+ ", $idx + 1) . "<ins>" . trim($val) . "</ins>";
  43. $diff = array_merge($w2, $o2);
  44. ksort($diff);
  45. return implode("\n", $diff);
  46. }
  47. }
  48. if (!function_exists('throw_validation_if')) {
  49. function throw_validation_if($condition, ...$parameters)
  50. {
  51. return throw_if($condition, \App\Exceptions\ValidationException::class, ...$parameters);
  52. }
  53. }
  54. if (!function_exists('make_array_list')) {
  55. function make_array_list(string $value): array
  56. {
  57. $array = [];
  58. if ($value == '') {
  59. return $array;
  60. }
  61. $array = explode(',', $value);
  62. $array = array_filter($array, function ($value) {
  63. return $value !== '';
  64. });
  65. $array = array_map(function ($value) {
  66. return intval($value);
  67. }, $array);
  68. return ($array);
  69. }
  70. }
  71. if (!function_exists('json_decode_arr')) {
  72. /**
  73. * 让json decode统一返回array
  74. * @param mixed $string
  75. * @return array
  76. */
  77. function json_decode_arr($string): array
  78. {
  79. $arr = json_decode($string, true);
  80. if (is_null($arr)) {
  81. $arr = [];
  82. }
  83. return $arr;
  84. }
  85. }