gpt4 book ai didi

php - 如何将多维数组中的所有键转换为 snake_case?

转载 作者:可可西里 更新时间:2023-11-01 12:28:58 25 4
gpt4 key购买 nike

我正在尝试将多维数组的键从 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;
}

关于php - 如何将多维数组中的所有键转换为 snake_case?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1444484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com