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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?