hy-farm/muchang/common/utils/CommUtil.php
2026-05-29 19:54:56 +08:00

162 lines
3.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Created by PhpStorm.
* User: zn
* Date: 2017/5/16
* Time: 19:04
*/
namespace common\utils;
use DateTime;
class CommUtil
{
/**
* 通过路径方式读取数组参数
* @param $dataList array源数据
* @param $keyPath 参数取值路径,使用点号分割 "init.gold"
* @param null $defaultValue
* @return null
*/
public static function getArrayParamByPath($dataList, $keyPath, $defaultValue = null)
{
if (!isset($keyPath)) return $defaultValue;
$keyPathList = explode(".", $keyPath);
$lastData = $dataList;
foreach ($keyPathList as $key) {
if (!isset($lastData[$key])) return $defaultValue;//字段不存在返回
$lastData = $lastData[$key];
}
return $lastData;
}
/**
* 格式化时间
* @param $time
* @return false|string
*/
public static function formatDate($time)
{
return date('Y-m-d H:i:s', $time);
}
public static function dayStr($time)
{
return date('Y-m-d', $time);
}
/**
* 获取周
* 以周一为标记
* @param int $time
* @return string | false
*/
public static function getWeek($time = 0)
{
if (empty($time))
$time = time();
$weekIndex = self::getWeekIndex($time);
$date = new DateTime();
$date->setTimestamp($time);
date_sub($date, date_interval_create_from_date_string($weekIndex . ' days'));
return date_format($date, "Y-m-d");
}
/**
* 获取周
* 以周一为标记
* @param int $time
* @return string | false
*/
public static function getWeekTime($time = 0)
{
$date = date_create(self::getWeek($time));
return $date->getTimestamp();
}
/**
* 获取周序号周一为0
* @param $time
* @return int
*/
public static function getWeekIndex($time)
{
return intval(date('N', $time)) - 1;
}
/**
* 每日凌晨时间
* @param $time
* @return int
*/
public static function getDayTime($time)
{
$dayStr = self::dayStr($time);
$date = date_create($dayStr);
return $date->getTimestamp();
}
/**
* 产生随机数字
* @param $len
* @return string
*/
public static function getRandomNum($len)
{
$code = '';
for ($i = 0; $i < $len; $i++) {
$code .= rand(0, 9);
}
return $code;
}
public static function oddsOne($list, $oddsField)
{
if (count($list) == 0) return null;
$totalOdds = 0;
$rlist = [];
foreach ($list as $item) {
$odds = intval($item[$oddsField]);
if ($odds == 0) continue;
$item['minOdds'] = $totalOdds;
$item['maxOdds'] = $odds + $totalOdds;
array_push($rlist, $item);
$totalOdds += $odds;
}
$odds = mt_rand(0, $totalOdds);
foreach ($rlist as $item) {
if ($item['minOdds'] <= $odds && $odds < $item['maxOdds'])
return $item;
}
return null;
}
public static function genUUID()
{
return md5(uniqid('', true));
}
public static function converStrList($delimiter, $str, $count)
{
$list = explode($delimiter, $str);
if (count($list) == 0) return null;
if ($count != 0 && count($list) != $count) return null;
return $list;
}
}