ArrayHelper.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Bear
  5. * Date: 2019/1/12
  6. * Time: 下午5:06
  7. */
  8. namespace app\common\helper;
  9. class ArrayHelper
  10. {
  11. /**
  12. * 按照数组权重获取索引
  13. * @param $proportion
  14. * @return mixed
  15. */
  16. public static function getRateFromArray($proportion)
  17. {
  18. $weight_total = 10000;
  19. $total = array_sum($proportion);
  20. if(!$total){
  21. return false;
  22. }
  23. $rat = $weight_total / $total;
  24. $ids = array_keys($proportion);
  25. $values = array_values($proportion);
  26. array_multisort($values, $ids);
  27. foreach ($values as $index => $weight) {
  28. if ($index == 0) {
  29. $values[$index] *= $rat;
  30. } else {
  31. $values[$index] = $values[$index] * $rat + $values[$index - 1];
  32. }
  33. $id = $ids[$index];
  34. }
  35. $value = rand(0, $weight_total);
  36. foreach ($values as $index => $weight) {
  37. if ($value < $weight && $weight != 0) {
  38. $id = $ids[$index];
  39. break;
  40. }
  41. }
  42. return $id;
  43. }
  44. /**
  45. * 从数组中制取元素
  46. * @param $array
  47. * @param $keys
  48. * @param null $callback_key
  49. * @return array
  50. */
  51. public static function extractFromArray($array, $keys, $callback_key = NULL)
  52. {
  53. $return = [];
  54. foreach ($keys as $key) {
  55. if (array_key_exists($key, $array)) {
  56. if ($callback_key instanceof \Closure) {
  57. $newKey = $callback_key($key);
  58. } else {
  59. $newKey = $key;
  60. }
  61. $return[$newKey] = $array[$key];
  62. }
  63. }
  64. return $return;
  65. }
  66. /**
  67. * 数组key替换为驼峰命令
  68. * @param $array
  69. * @return array
  70. */
  71. public static function replaceKeyWithCamel($array)
  72. {
  73. $result = [];
  74. foreach ($array as $index => $item) {
  75. $newKey = StringHelper::stringToCamel($index);
  76. $result[$newKey] = $item;
  77. }
  78. return $result;
  79. }
  80. /**
  81. * @param $array
  82. * @param $key
  83. * @param string $default
  84. * @return string
  85. */
  86. public static function arrayGet($array, $key, $default = '')
  87. {
  88. if (!is_array($array)) {
  89. $array = [];
  90. }
  91. if (array_key_exists($key, $array)) {
  92. return $array[$key];
  93. }
  94. return $default;
  95. }
  96. }