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

时间:2022-08-05 10:38:58

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".

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

any ideas?

有任何想法吗?

3 个解决方案

#1


4  

A simple foreach loop should suffice:

一个简单的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


2  

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

is what i was looking for.

是我在寻找的。

#3


2  

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.

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

#1


4  

A simple foreach loop should suffice:

一个简单的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


2  

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

is what i was looking for.

是我在寻找的。

#3


2  

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.

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