我正在尝试创建一个函数来转换 Multidemnsional 数组中的所有键(从/到)驼峰式大小写。问题是当我有一个数组数组时,内部数组作为数组的最后一个元素出现,我不知道为什么..
这是功能:
function transformKeys(&$array, $direction = 'to')
{
if (is_array($array)) {
foreach (array_keys($array) as $key) {
$value = &$array[$key];
unset($array[$key]);
if ($direction == 'to')
$transformedKey = toCamelCase($key);
else
$transformedKey = fromCamelCase($key);
if (is_array($value))
transformKeys($value, $direction);
if (isset($array[$transformedKey]) && is_array($array[$transformedKey])) {
$array[$transformedKey] = array_merge($array[$transformedKey], $value);
}
else
$array[$transformedKey] = $value;
unset($value);
}
}
return $array;
}
function toCamelCase($string, $sepp = '_')
{
$str = str_replace(' ', '', ucwords(str_replace($sepp, ' ', $string)));
$str[0] = strtolower($str[0]);
return $str;
}
function fromCamelCase($string, $sepp = '_')
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $string, $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode($sepp, $ret);
}
数组是这样的..
{
"id": 23,
"name": "FOO SA",
"taxIdentifier_id": "309",
"activityType": "UTILITY",
"currencyCode": "USD",
"contacts": [
{
"id": 7,
"firstName": "Bla",
"lastName": "Bla",
"gender": "M",
"supplierId": 23
},
{
"id": 8,
"firstName": "Another",
"lastName": "Value",
"gender": "M",
"supplierId": 23
}
]
}
结果……
Array
(
[id] => 23
[name] => FOO SA
[tax_identifier_id] => 309
[activity_type] => UTILITY
[currency_code] => USD
[contacts] => Array
(
[] => Array
(
[id] => 8
[first_name] => Another
[last_name] => Value
[gender] => M
[supplier_id] => 23
)
)
)
有任何想法吗??
谢谢!