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] => 
    )
)

我想将“距离”的所有实例命名为“近”。

有任何想法吗?

4

3 回答 3

4

A simple foreach loop should suffice:

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]);
    }
}
于 2009-12-14T11:01:22.543 回答
4

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

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

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

于 2009-12-14T11:30:10.347 回答
2
foreach($_GET as $key=>$val){
    $DATA[str_replace("distance", "near", $key)] = $val;
}

是我一直在寻找的。

于 2009-12-14T10:57:39.697 回答