2009-12-14 27 views
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] => 
    ) 
) 

我要命名的“距离”的所有实例,以“近”。

有什么想法?

+0

嗯,我以为你应该使用你的IDE重命名功能来完成这项工作? – Graviton 2009-12-14 10:49:34

+1

我想让PHP为我重命名密钥 – dotty 2009-12-14 10:51:23

回答

4

一个简单的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]); 
    } 
} 
2
foreach($_GET as $key=>$val){ 
    $DATA[str_replace("distance", "near", $key)] = $val; 
} 

是我一直在寻找。

+0

请记住,此解决方案不是递归的。 – 2009-12-14 11:32:11

2

这里是不使用循环的溶液:

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

作为额外的奖励它处理多维数组,唯一的缺点如果任何数组值中有“distance_”,它也将被转换,但不知何故,我不认为这对你来说是一个问题。