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条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料