duanjiaolao1187 2012-12-03 10:40
浏览 32
已采纳

在PHP中,如何在不移动数组键的情况下重命名数组键?

I need to write an array in a CSV file where column order must not be changed. But I want to reduce column titles to a length of max 64 chars. To make the question more general, let's take a simple example :

$array = array(
    'A te' => 'foo A',
    'Q test' => 'foo Q',
    'Z test' => 'foo Z',
);

var_dump($array);

Give :

array (size=3)
  'A te' => string 'foo A' (length=5)
  'Q test' => string 'foo Q' (length=5)
  'Z test' => string 'foo Z' (length=5)

Now, I want to rename the "Q test" key to "Q tes". If I do :

$swap = $array["Q test"];
unset($array["Q test"]);
$array["Q tes"] = $swap;
var_dump($array);

Displays :

array (size=3)
  'A te' => string 'foo A' (length=5)
  'Z test' => string 'foo Z' (length=5)
  'Q tes' => string 'foo Q' (length=5)

The column's position changed, that's not what I was looking for.

I solved my problem by using (here, reducing keys to 5 chars) :

$keys = array_keys($array);
$values = array_values($array);
$count = count($keys);
for ($i = 0; ($i < $count); $i++)
{
   if (mb_strlen($keys[$i]) > 5)
   {
      $keys[$i] = mb_substr($keys[$i], 0, 5);
   }
}
$array = array_combine($keys, $values);

var_dump($array);

Outputs:

array (size=3)
  'A te' => string 'foo A' (length=5)
  'Q tes' => string 'foo Q' (length=5)
  'Z tes' => string 'foo Z' (length=5)

But this looks very resources-devour... I do need to execute such a code on each of my rows, and I have from 10k to 100k rows.

Is there a simpler way to rename array keys without moving them?

  • 写回答

1条回答 默认 最新

  • dphfwzn8269 2012-12-03 10:46
    关注

    Try this, which should be simpler,

    foreach($array as $k=>$v){
       if($k=='Q test'){
          $new_arr['Q tes'] = $array['Q test'];
       }else{
          $new_arr[$k] = $v;
       }
    }
    
    print_r($new_arr); //set $array = $new_arr;  to overwrite all values
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改