function array_snake_case($array) { if (!is_array($array)) { return false; } $return = array(); foreach ($array as $key => &$value) { if (strpos($key, '_') === false && !is_int($key)) { preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $key, $matches); foreach ($matches[0] as &$match) { $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match); } $newKey = implode('_', $matches[0]); } else { $newKey = $key; } if (is_array($value)) { $newValue = array_snake_case($value); } else { $newValue = $value; } $return[$newKey] = $newValue; } return $return; }
/** * Test function array_snake_case() * * @dataProvider snakeCaseProvider */ public function testArraySnakeCase($test, $expected) { $this->assertEquals($expected, array_snake_case($test)); }