数组

判断这个值是否在函数内

$allowedIds = [41, 67, 95, 96];

in_array(95,$allowedIds)

从数组中提取某一列的值

$ids = array_column($items, 'id');

添加两位小数

number_format($value['amount'], 2, '.', '');

查找数组的某个数组的和,计算平均值

// 计算总和与平均值
$sum = array_reduce($data, function ($carry, $item) {
     return $carry + ($item['amount'] ?? 0);
}, 0);

$item['amount'] = count($data) > 0 ? $sum / count($data) : $item['amount'];

数组根据某值排序

降序只需要把$a和$b到位置调换就行

//排序
usort($list, function($a, $b) {
    return ($a['order'] ?: PHP_INT_MAX) <=> ($b['order'] ?: PHP_INT_MAX);
});

这个适用于两层数组

//排序
uasort($list, function($a, $b) {
    return ($a['order'] ?: PHP_INT_MAX) <=> ($b['order'] ?: PHP_INT_MAX);
});

字符串转数组

转数组

explode(',', $input);

去除空格并转数组

$array = array_map('trim', explode(',', $input));

转为整数并转数组

$array = array_map('intval', explode(',', $input));

处理空值并转数组

$array = array_filter(explode(',', $input));

筛选

筛选数组不含有测试的数据(筛选含有就把第一个=换成!)

$deviceList = array_filter($deviceList, function ($item) {
    return mb_strpos($item['name'], '测试') === false;
})

查找两个数组并合并

$list = array_merge(
    filterArray(CoachModel::list(), 'store_id', $storeId),
    array_filter(
        filterArray(CoachModel::list(), 'store_id', 0),
        fn($item) => !empty($item['workplace']) && in_array($storeId, explode(",", $item['workplace']))
    )
);

时间处理

//获取当前时间的分
date('i', time());
//获取当前时间的30分的时间戳
$bbb = strtotime(date('Y-m-d H:30:00', time()));

//获取当天时间戳
strtotime(date('Y-m-d'));

状态码

400 Bad Request
当请求无法被服务器理解或处理时使用。例如,请求缺少必要的参数或参数格式错误等。
401 Unauthorized
当请求需要用户身份验证时使用。如果用户未通过身份验证,则应该返回此状态码。
403 Forbidden
当请求被理解但服务器拒绝执行时使用。这通常是因为用户权限不足。
404 Forbidden
当请求不存在的数据时执行时使用
409 Conflict
当请求不能完成因为它是冲突的。例如,当试图创建一个已经存在的资源时。
422 Unprocessable Entity (WebDAV extensions)
当请求被服务器理解但是不能被处理时使用。通常用于语义错误的情况,比如数据违反了约束条件。
500 Internal Server Error
当服务器遇到一个未曾预料的情况,无法完成对请求的处理时使用。这通常意味着服务器内部出现了错误。
最后修改:2025 年 02 月 14 日
如果觉得我的文章对你有用,请随意赞赏