123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Bear
- * Date: 2019/1/12
- * Time: 下午5:06
- */
- namespace app\common\helper;
- class ArrayHelper
- {
- /**
- * 按照数组权重获取索引
- * @param $proportion
- * @return mixed
- */
- public static function getRateFromArray($proportion)
- {
- $weight_total = 10000;
- $total = array_sum($proportion);
- if(!$total){
- return false;
- }
- $rat = $weight_total / $total;
- $ids = array_keys($proportion);
- $values = array_values($proportion);
- array_multisort($values, $ids);
- foreach ($values as $index => $weight) {
- if ($index == 0) {
- $values[$index] *= $rat;
- } else {
- $values[$index] = $values[$index] * $rat + $values[$index - 1];
- }
- $id = $ids[$index];
- }
- $value = rand(0, $weight_total);
- foreach ($values as $index => $weight) {
- if ($value < $weight && $weight != 0) {
- $id = $ids[$index];
- break;
- }
- }
- return $id;
- }
- /**
- * 从数组中制取元素
- * @param $array
- * @param $keys
- * @param null $callback_key
- * @return array
- */
- public static function extractFromArray($array, $keys, $callback_key = NULL)
- {
- $return = [];
- foreach ($keys as $key) {
- if (array_key_exists($key, $array)) {
- if ($callback_key instanceof \Closure) {
- $newKey = $callback_key($key);
- } else {
- $newKey = $key;
- }
- $return[$newKey] = $array[$key];
- }
- }
- return $return;
- }
- /**
- * 数组key替换为驼峰命令
- * @param $array
- * @return array
- */
- public static function replaceKeyWithCamel($array)
- {
- $result = [];
- foreach ($array as $index => $item) {
- $newKey = StringHelper::stringToCamel($index);
- $result[$newKey] = $item;
- }
- return $result;
- }
- /**
- * @param $array
- * @param $key
- * @param string $default
- * @return string
- */
- public static function arrayGet($array, $key, $default = '')
- {
- if (!is_array($array)) {
- $array = [];
- }
- if (array_key_exists($key, $array)) {
- return $array[$key];
- }
- return $default;
- }
- }
|