Skip to content

Instantly share code, notes, and snippets.

@madmuffin1
Forked from goldsky/transformKeys.php
Last active December 21, 2015 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madmuffin1/3fbfae54e2aa537fbc9b to your computer and use it in GitHub Desktop.
Save madmuffin1/3fbfae54e2aa537fbc9b to your computer and use it in GitHub Desktop.
Convert under_score type array's keys to camelCase type array's keys and likewise
<?php
/**
* Convert under_score type array's keys to camelCase type array's keys
* @param array $array array to convert
* @return array camelCase array
*/
public function camelCaseKeys($array) {
$camelCaseArray = array();
foreach ($array as $key => $val) {
$newKey = @explode('_', $key);
array_walk($newKey, create_function('&$v', '$v = ucwords($v);'));
$newKey = @implode('', $newKey);
$newKey{0} = strtolower($newKey{0});
if (!is_array($val)) {
$camelCaseArray[$newKey] = $val;
} else {
$camelCaseArray[$newKey] = $this->camelCaseKeys($val);
}
}
return $camelCaseArray;
}
/**
* Convert camelCase type array's keys to under_score+lowercase type array's keys
* @param array $array array to convert
* @return array under_score array
*/
public function underscoreKeys($array) {
$underscoreArray = array();
foreach ($array as $key => $val) {
$newKey = preg_replace('/[A-Z]/', '_$0', $key);
$newKey = strtolower($newKey);
$newKey = ltrim($newKey, '_');
if (!is_array($val)) {
$underscoreArray[$newKey] = $val;
} else {
$underscoreArray[$newKey] = $this->underscoreKeys($val);
}
}
return $underscoreArray;
}
/**
* Convert camelCase type array's values to under_score+lowercase type array's values
* @param mixed $mixed array|string to convert
* @return mixed under_score array|string
*/
public function underscoreValues($mixed) {
$underscoreArray = array();
if (!is_array($mixed)) {
$newVal = preg_replace('/[A-Z]/', '_$0', $mixed);
$newVal = strtolower($newVal);
$newVal = ltrim($newVal, '_');
return $newVal;
} else {
foreach ($mixed as $key => $val) {
$underscoreArray[$key] = $this->underscoreValues($val);
}
return $underscoreArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment