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

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名