doubu5035 2012-07-20 16:40 采纳率: 100%
浏览 235
已采纳

PHP - 关联数组:更改键值对的键,其中value是类对象

I have an associative array of the form:

$input = array("one" => <class object1>,
               "two" => <class object2,
               ... //and so on);

The keys of $input are guaranteed to be unique. I also have a method called moveToHead($key) which moves the $input[$key] element to the 0th location of this associative array. I have few questions:

  1. Is it possible to determine the index of an associative array?
  2. How to move the array entry for corresponding $key => $value pair to the index 0 and retaining the $key as is?
  3. What could be the best possible way to achieve both of the above points?

I was thinking to do array_flip for 2nd point (a sub solution), but later found out that array_flip can only be done when array elements are int and string only. Any pointers?

  • 写回答

4条回答 默认 最新

  • doumei3828 2012-07-20 16:55
    关注

    With a function called array_keys you can determine the index of a key:

    $keys = array_flip(array_keys($input));
    printf("Index of '%s' is: %d
    ", $key, $keys[$key]);
    

    To insert an array at a certain position (for example at the beginning), there is the array_splice function. So you can create the array to insert, remove the value from the old place and splice it in:

    $key = 'two';
    $value = $input[$key];
    unset($input[$key]);    
    array_splice($input, 0, 0, array($key => $value));
    

    Something similar is possible with the array union operator, but only because you want to move to the top:

    $key = 'two';
    $value = $input[$key];
    unset($input[$key]);
    $result = array($key => $value) + $input;
    

    But I think this might have more overhead than array_splice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 PCB设计与制作问答
  • ¥20 课堂跑如何下载ppt
  • ¥15 有没有哥看着画下电路
  • ¥15 STM32阿里云平台显示不了传感器采集的数据
  • ¥20 三菱FX系列PLC上位机串口下指令置位M64和M65,这两条指令分别是什么呢?
  • ¥15 有关结冰模拟程序咨询
  • ¥15 ubuntu服务器配置dns域名后无法访问其他域名
  • ¥50 本人复制了一个关于股票指标的代码,但是运行失败,有没有人帮我解决一下
  • ¥50 用matlab和numeca做透平机械流体力学和热力学模拟 价格可议
  • ¥15 Unity3D WebView