doulangxun7769 2013-05-28 20:00
浏览 45
已采纳

PHP中的队列数组[关闭]

I want to implement a queue in PHP, and looking at the manual , I found this example:

$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);

This creates the array:

array('apple', 'raspberry', 'orange', 'banana');

In this case 'banana' is at the beginning of the queue and it can be retrieved using array_pop().

I guess that might be the traditional approach, but is there any good reason for not reversing the data in the array as follows?

$queue = array('apple', 'orange');
$queue[] = 'banana';//avoid function call
array_push($queue, 'strawberry', 'grape');//add multiple items
$next = array_shift($queue);

Maybe it's trivial, but in that way you could avoid a function call when adding a single element. Is there some other good reason for not doing it that way?

EDIT:

It appears that my question was a little hard to understand, so to make it easier to see that my method really does implement a queue according to the FIFO principle, I wrote this code to correspond with the example from the PHP manual, producing the exact same array (except in reverse order):

$queue = array('banana', 'orange');
$queue[] = 'rasberry';
$queue[] = 'apple';

This creates the array:

array('banana', 'orange', 'rasberry', 'apple');

It's the exact same data but in reverse order, so to retreive the next item you would do so with:

$next = array_shift($queue);//The value of $next is 'banana' as before.

As already pointed out by the answers, this runs up against how most people visualize a queue. It seems that readability is the major issue. However, I find it easier to code. To me, it actually seems more natural, because the square bracket notation [] is the doorway through which my array elements enter in numerous circumstances. Therefore, implementing either a stack or a queue really isn't a question about how I mentally visualize my data. It's a question of what function to use to access the first or last element that passed through the door. For a queue it's array_shift(), and for a stack it's pop().

  • 写回答

2条回答 默认 最新

  • dst2007 2013-05-28 20:09
    关注

    I would do it the first way (shortest code, easiest to follow) unless you have a specific and valid reason for using the second approach. While $queue[] = 'banana' may be faster (I believe it is but don't know for sure), the difference is so small that you shouldn't worry about it unless you're doing millions of operations or something where it would actually make a difference.

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

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题