views:

186

answers:

3

Hay all, i have an array

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

i want to name all instances of "distance" to "near".

any ideas?

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

is what i was looking for.

dotty
Bear in mind that this solution is not recursive.
Alix Axel
+3  A: 

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]);
    }
}
Dominic Barnes
A: 

Here is a solution that doesn't uses loops:

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

As a added bonus it handles multi-dimensional arrays, the only drawback is that if any of the array values has "distance_" in it, it will also be converted, but somehow I don't think this is a problem for you.

Alix Axel