php – 如何将多维数组中的所有键转换为snake_case?
发布时间:2020-12-13 22:40:36 所属栏目:PHP教程 来源:网络整理
导读:我试图将多维数组的键从CamelCase转换为snake_case,增加的复杂性是某些键有一个我想删除的感叹号. 例如: $array = array( '!AccountNumber' = '00000000','Address' = array( '!Line1' = '10 High Street','!line2' = 'London')); 我想转换为: $array = ar
我试图将多维数组的键从CamelCase转换为snake_case,增加的复杂性是某些键有一个我想删除的感叹号.
例如: $array = array( '!AccountNumber' => '00000000','Address' => array( '!Line1' => '10 High Street','!line2' => 'London')); 我想转换为: $array = array( 'account_number' => '00000000','address' => array( 'line1' => '10 High Street','line2' => 'London')); 我现实生活中的阵列非常庞大,深入人心.任何帮助如何处理这一点非常感谢!
这是我使用的修改函数,取自soulmerge的响应:
function transformKeys(&$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 = strtolower(preg_replace('/([a-z])([A-Z])/','$1_$2',ltrim($key,'!'))); # Work recursively if (is_array($value)) transformKeys($value); # Store with new key $array[$transformedKey] = $value; # Do not forget to unset references! unset($value); endforeach; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |