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

前端之家收集整理的这篇文章主要介绍了php – 如何将多维数组中的所有键转换为snake_case?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将多维数组的键从CamelCase转换为snake_case,增加的复杂性是某些键有一个我想删除的感叹号.

例如:

  1. $array = array(
  2. '!AccountNumber' => '00000000','Address' => array(
  3. '!Line1' => '10 High Street','!line2' => 'London'));

我想转换为:

  1. $array = array(
  2. 'account_number' => '00000000','address' => array(
  3. 'line1' => '10 High Street','line2' => 'London'));

我现实生活中的阵列非常庞大,深入人心.任何帮助如何处理这一点非常感谢!

这是我使用的修改函数,取自soulmerge的响应:
  1. function transformKeys(&$array)
  2. {
  3. foreach (array_keys($array) as $key):
  4. # Working with references here to avoid copying the value,# since you said your data is quite large.
  5. $value = &$array[$key];
  6. unset($array[$key]);
  7. # This is what you actually want to do with your keys:
  8. # - remove exclamation marks at the front
  9. # - camelCase to snake_case
  10. $transformedKey = strtolower(preg_replace('/([a-z])([A-Z])/','$1_$2',ltrim($key,'!')));
  11. # Work recursively
  12. if (is_array($value)) transformKeys($value);
  13. # Store with new key
  14. $array[$transformedKey] = $value;
  15. # Do not forget to unset references!
  16. unset($value);
  17. endforeach;
  18. }

猜你在找的PHP相关文章