我试图将多维数组的键从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的响应:
原文链接:https://www.f2er.com/php/133263.htmlfunction 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; }