开发者

regex on an array to rename keys

开发者 https://www.devze.com 2022-12-14 10:35 出处:网络
Hay all, i have an array Array ([near_prescription] => Array ( [go_to] => inter_selection [distance_right_sph] 开发者_如何学Go=> 0.00

Hay all, i have an array

Array ([near_prescription] => Array (
    [go_to] => inter_selection 
    [distance_right_sph] 开发者_如何学Go=> 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?


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]);
    }
}


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.


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

is what i was looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消