首頁 >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