【问题标题】:regex on an array to rename keys数组上的正则表达式以重命名键
【发布时间】:2010-12-26 09:22:16
【问题描述】:

大家好,我有一个数组

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

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

有什么想法吗?

【问题讨论】:

  • 嗯,我认为您应该使用您的 IDE 重命名功能来完成这项工作?
  • 我希望 PHP 为我重命名密钥

标签: php regex arrays rename


【解决方案1】:
foreach($_GET as $key=>$val){
    $DATA[str_replace("distance", "near", $key)] = $val;
}

是我一直在寻找的。​​p>

【讨论】:

    【解决方案2】:

    一个简单的 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]);
        }
    }
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-03
        • 2014-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-31
        • 2016-03-20
        相关资源
        最近更新 更多