Convert to camel case and snake case in php:
In php, if we want to convert camel case to snake case and vise versa then we have to use following methods:public static function convertToCamelCase($array) {
$converted_array = [];
foreach ($array as $old_key => $value) {
if (is_array($value)) {
$value = static::convertToCamelCase($value);
} else if (is_object($value)) {
if (method_exists($value, 'toArray')) {
$value = $value->toArray();
} else {
$value = (array) $value;
}
$value = static::convertToCamelCase($value);
}
$converted_array[camel_case($old_key)] = $value;
}
return $converted_array;
}
public static function convertToSnakeCase($array) {
$converted_array = [];
foreach ($array as $old_key => $value) {
if (is_array($value)) {
$value = static::convertToSnakeCase($value);
} else if (is_object($value)) {
if (method_exists($value, 'toArray')) {
$value = $value->toArray();
} else {
$value = (array) $value;
}
$value = static::convertToSnakeCase($value);
}
$new_key = ltrim(strtolower(preg_replace('/[A-Z]/', '_$0', $old_key)), '_');
$converted_array[$new_key] = $value;
}
return $converted_array;
}
This will help for this.
No comments:
Post a Comment