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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助