Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert all keys in a multi-dimenional array to snake_case?

I am trying to convert the keys of a multi-dimensional array from CamelCase to snake_case, with the added complication that some keys have an exclamation mark that I'd like removed.

For example:

$array = array(
  '!AccountNumber' => '00000000',
  'Address' => array(
    '!Line1' => '10 High Street',
    '!line2' => 'London'));

I would like to convert to:

$array = array(
  'account_number' => '00000000',
  'address' => array(
    'line1' => '10 High Street',
    'line2' => 'London'));

My real-life array is huge and goes many levels deep. Any help with how to approach this is much appreciated!

like image 653
aaronrussell Avatar asked Sep 18 '09 13:09

aaronrussell


1 Answers

Here's a more generalized version of Aaron's. This way you can just plug the function you want to be operated on for all keys. I assumed a static class.

public static function toCamelCase ($string) {
  $string_ = str_replace(' ', '', ucwords(str_replace('_',' ', $string)));
  return lcfirst($string_);
}

public static function toUnderscore ($string) {
  return strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
}

// http://stackoverflow.com/a/1444929/632495
function transformKeys($transform, &$array) {
  foreach (array_keys($array) as $key):
    # Working with references here to avoid copying the value,
    # since you said your data is quite large.
    $value = &$array[$key];
    unset($array[$key]);
    # This is what you actually want to do with your keys:
    #  - remove exclamation marks at the front
    #  - camelCase to snake_case
    $transformedKey = call_user_func($transform, $key);
    # Work recursively
    if (is_array($value)) self::transformKeys($transform, $value);
    # Store with new key
    $array[$transformedKey] = $value;
    # Do not forget to unset references!
    unset($value);
  endforeach;
}

public static function keysToCamelCase ($array) {
  self::transformKeys(['self', 'toCamelCase'], $array);
  return $array;
}

public static function keysToUnderscore ($array) {
  self::transformKeys(['self', 'toUnderscore'], $array);
  return $array;
}
like image 104
Jon49 Avatar answered Sep 19 '22 15:09

Jon49