PHP更新数组索引/键

时间:2015-03-05 08:20:16

标签: php

我有一个数组,并希望将其数组键从驼峰大小写转换为下划线大小写。如何做到这一点?

$before = ['ThisIsATest' => 'Something', 'cheeseCake' => 'Something else'];
$after = ['this_is_a_test' => 'Something', 'cheese_cake' => 'Something else'];

我主要想知道如何更新数组键!


根据您的输入,我创建了以下两个功能:

function camelToUnderscore($string)
{
    if (is_numeric($string)) {
        return $string;
    }

    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('_', $ret);
}

function keysCamelToUnderscore(array $array)
{
    $newArray = [];

    foreach ($array AS $key => $value) {

        if (!is_array($value)) {
            unset($array[$key]);
            $newArray[camelToUnderscore($key)] = $value;
        } else {
            unset($array[$key]);
            $newArray[camelToUnderscore($key)] = keysCamelToUnderscore($value);
        }
    }

    return $newArray;
}

0 个答案:

没有答案