首页 >php教程 >PHP源码 >驼峰对象转下划线数组和下划线数组转驼峰对象

驼峰对象转下划线数组和下划线数组转驼峰对象

WBOY
WBOY原创
2016-08-04 08:53:361956浏览
跳至 [1] [2] [全屏预览]
    /***
     * @param $fields 驼峰对象
     * @return array
     */
    public static function CamelToUnderLineArr($fields)
    {
        $newArr = [];
        if (!is_object($fields) || !get_object_vars($fields))  return $newArr;

        foreach ($fields as $key => $v) {
            $keyTmp = strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $key));
            $newArr[$keyTmp] = $v;
            unset($fields->$key);
        }

        return $newArr;
    }

2. [代码]下划线数组转驼峰对象     跳至 [1] [2] [全屏预览]

    /***
     * @param $fields 下划线数组
     * @return \stdClass
     */
    public static function underLineArrTOCamel($fields)
    {

        $newObj = new \stdClass();
        if(!is_array($fields) || !$fields) return null;
        foreach ($fields as $key => $v) {
            $keyTmp = array_reduce(explode('_',$key), function($v1, $v2) {
                return ucfirst($v1).ucfirst($v2);
            });
            $keyTmp = lcfirst($keyTmp);
            $newObj->$keyTmp = $v;
            unset($fields[$key]);
        }
        return $newObj;
    }
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn