转换书写风格的方案均基于递归深度遍历,对key值重新建构,将value值重新赋值。
让我们一起来看看以下详细代码实现。
- 下划线风格=>驼峰风格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| <?php
public static function arrKeysToCamelCase($in) { if(empty($in)||!is_array($in)) return $in; $reCopyRes = array(); foreach($in as $key=>$val) { $reKey = self::ucFirstWord($key); if(!is_array($val)){ $reCopyRes[$reKey] = $val; }else{ $reCopyRes[$reKey] = self::arrKeysToCamelCase($val); } } return $reCopyRes; }
public static function ucFirstWord($word) { if(!is_string($word)){ return $word; }else{ $wordArr = explode('_',$word); if(!empty($wordArr)){ $index = 0; foreach($wordArr as &$wd) { if($index==0){ $index++; continue; } $wd = ucfirst($wd); } $outStr = implode('',$wordArr); return $outStr; }else{ return $word; } } }
|
- 驼峰风格=>下划线风格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <?php
public static function arrKeysToUnderlineCase($in) { if(empty($in)||!is_array($in)) return $in; $reCopyRes = array(); foreach($in as $key=>$val) { $reKey = self::lcFirstWord($key); if(!is_array($val)){ $reCopyRes[$reKey] = $val; }else{ $reCopyRes[$reKey] = self::arrKeysToUnderlineCase($val); } } return $reCopyRes; }
public static function lcFirstWord($word) { if(!is_string($word)){ return $word; }else{ preg_match_all('/([a-z0-9_]*)([A-Z][a-z0-9_]*)?/',$word,EG_PATTERN_ORDER); if(!empty($matches)){ $strPattern1 = !empty($matches[1][0])?trim($matches[1][0]):''; $subMatch = array_filter($matches[2]); $strPattern2 = !empty($subMatch)?trim(implode('_',$subMatch)):''; $strPattern2 = !empty($strPattern2) && !empty($strPattern1)?'_'.2:$strPattern2; $outStr = strtolower($strPattern1.$strPattern2); }else{ $outStr = $word; } return $outStr; } }
|