Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用于重命名键的数组上的正则表达式_Php_Regex_Arrays_Rename - Fatal编程技术网

Php 用于重命名键的数组上的正则表达式

Php 用于重命名键的数组上的正则表达式,php,regex,arrays,rename,Php,Regex,Arrays,Rename,嗨,我有一个数组 Array ([near_prescription] => Array ( [go_to] => inter_selection [distance_right_sph] => 0.00 [balance_right] => [distance_right_cyl] => 0.00 [distance_right_axis] => [distance_left_sph] => 0.

嗨,我有一个数组

Array ([near_prescription] => Array (
    [go_to] => inter_selection 
    [distance_right_sph] => 0.00
    [balance_right] => 
    [distance_right_cyl] => 0.00 
    [distance_right_axis] => 
    [distance_left_sph] => 0.00 
    [balance_left] => 
    [distance_left_cyl] => 0.00 
    [distance_left_axis] => 
    )
)
我想将“距离”的所有实例命名为“近”

有什么想法吗

foreach($_GET as $key=>$val){
    $DATA[str_replace("distance", "near", $key)] = $val;
}

这就是我想要的。

一个简单的foreach循环就足够了:

foreach ($array as $key => $value)
{
    # If the key name contains 'distance_'
    if (strpos($key, 'distance_') !== false)
    {
        # Create a new, renamed, key. Then assign it the value from before
        $array[str_replace('distance_', 'near_', $key)] = $value;

        # Destroy the old key/value pair
        unset($array[$key]);
    }
}

以下是一个不使用循环的解决方案:

$array = json_decode(str_replace('distance_', 'near_', json_encode($array)), true);

作为一个额外的好处,它处理多维数组,唯一的缺点是,如果数组值中有“距离”,它也会被转换,但不知何故,我不认为这对您是一个问题。

Hmm,我认为您应该使用IDE重命名函数来完成这项工作?我希望PHP为我重命名键