-- 创造无限可能

PHP实用小技巧:数组key 驼峰/下划线 互转

2022-10-14 19:27:55
571 人浏览 1 人点赞
有用,点赞支持一下

驼峰转下划

function HumpToUnderline($params) {
    $newArr = [];
    if (!is_array($params) || empty($params)) return $newArr;
    foreach ($params as $key => $val){
        $newkey = $key;
        if (!strstr($key, '_')) {
            $key = str_replace("_", "", $key);
            $key = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
            return '_' . strtolower($matches[0]);
            }, $key);
            $newkey = ltrim($key, "_");
        }

        $newArr[$newkey] = is_array($val) ? humpUnderlineConversion($val, $type) : $val;
    }

    return $newArr;
}

下划线转驼峰

function UnderlineToHump($params) {
    $newArr = [];
    if (!is_array($params) || empty($params)) return $newArr;
    foreach ($params as $key => $val){
        $newkey = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
            return strtoupper($matches[2]);
        }, $key);
        $newArr[$newkey] = is_array($val) ? humpUnderlineConversion($val, $type) : $val;
    }

    return $newArr;
}