Home > php教程 > PHP源码 > body text

CamelCase object to underscore array and underscore array to camelCase object

WBOY
Release: 2016-08-04 08:53:36
Original
1931 people have browsed it
Jump to [1] [2] [Full screen preview]
    /***
     * @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;
    }
Copy after login

2. [Code]Convert underline array to camel case object Jump to [1] [2] [Full screen preview]

    /***
     * @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;
    }
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template