dongwei1855 2010-01-04 20:00
浏览 35
已采纳

如何获取我知道在数组中唯一的键的索引

I have a list of items in a particular order so I've decided to store them in an array

$items = array(
   "apple",
   "banana",
   "pear"
);

If the program is called with the parameter "banana" I need to be able to say "apple" comes before and "pear" comes after. Currently I'm doing something like this:

foreach($items as $k=>$v) { if ($v == "banana") { $current_key = $k }

So now I know that $current_key -1 is previous and +1 is next. It works, it just FEELS ugly to iterate over the entire array. Is there a better way to do this?

UPDATE In case anyone cares, I decided to do a few quick tests to see how fast the ways of getting the information were. Over 1000 iterations, on an array of 6000 items, microtime retunred:

My Posted Way: 4.567 Array_Search: 2.749

While I was thinking I also tried an approach that stored the data in a array of arrays like:

$items['banana']['next'] = 'pear';
$items['banana']['prev'] = 'apple';

which was, of course, the winner by miles ( 0.0005 ). None of this is really relevant, I was just curious and thought to share with anyone who reads this.

  • 写回答

3条回答 默认 最新

  • doujuanxun7167 2010-01-04 20:01
    关注

    array_search() should save you the loop.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?