本文介绍了如何将所有密钥转换在多dimenional阵列snake_case?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从一个驼峰多维数组的键转换为snake_case,用更加复杂,有些键有,我想删除一个感叹号。
I am trying to convert the keys of a multi-dimensional array from CamelCase to snake_case, with the added complication that some keys have an exclamation mark that I'd like removed.
例如:
$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'));
我的现实生活中的数组是巨大的,深刻的去很多层次。与如何处理任何帮助,这是非常AP preciated!
My real-life array is huge and goes many levels deep. Any help with how to approach this is much appreciated!
推荐答案
这是修改后的功能我都用过,从soulmerge的回应采取:
This is the modified function I have used, taken from soulmerge's response:
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;
}
这篇关于如何将所有密钥转换在多dimenional阵列snake_case?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!