Skip to content

Instantly share code, notes, and snippets.

@redbonzai
Created March 17, 2021 11:31
Show Gist options
  • Save redbonzai/875f35728ed71a654825a3968254f044 to your computer and use it in GitHub Desktop.
Save redbonzai/875f35728ed71a654825a3968254f044 to your computer and use it in GitHub Desktop.
<?php
namespace CSID\IMC\Baseline\CoreBundle\Model\Traits;
trait RecursiveSnakeCaseToCamelCaseKeys
{
/**
* Recursively iterate through an array with snake_case keys
* and convert those keys to camelCase.
* @param array $snakeCaseArray
* @return array
*/
public function recursiveSnakeCaseToCamelCaseKeys(array $snakeCaseArray): array
{
$result = [];
foreach ($snakeCaseArray as $key => $val) {
$newKey = $this->toCamelCase($key);
if (!is_array($val)) {
$result[$newKey] = $val;
} else {
$result[$newKey] = $this->recursiveSnakeCaseToCamelCaseKeys($val);
}
}
return $result;
}
/**
* Convert snake_case words to camelCase
* @param string $value
* @return string
*/
public function toCamelCase(string $value): string
{
$valueArray = explode('_', $value);
return $this->iterateSnakeCaseWordArray($valueArray);
}
/**
* Iterate through a word array
* Capitalize the first letter of every word
* Join each word.
* @param array $wordArray
* @return string
*/
public function iterateSnakeCaseWordArray(array $wordArray): string
{
$i = 0;
$capitalizedWords = [];
foreach ($wordArray as $word) {
$i === 0
? $capitalizedWords[] = $word
: $capitalizedWords[] = ucwords($word);
$i++;
}
return implode('', $capitalizedWords);
}
}
@redbonzai
Copy link
Author

This trait recursively converts snake_case keys to camelCase for multi-nested associative arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment