php - 当优先级不是整数时,SplPriorityQueue 如何工作?

标签 php spl

我想知道当优先级为stringintSplPriorityQueue如何工作。简单示例:

    $queue = new \SplPriorityQueue();

    $queue->insert('b', 5);
    $queue->insert('c', 5);
    $queue->insert('d', 1);
    $queue->insert('a', 10);
    $queue->insert('1', 'a');
    $queue->insert('2', 'b');

    print_r($queue);

输出:

Array
(
    [5] => a
    [4] => b
    [3] => c
    [2] => d
    [1] => 2
    [0] => 1
)

问题:为什么具有 int 优先级的项目会首先列出(即 a b c d)?当优先级为 string(项 1 2)时,b 是否被视为大于 a

最佳答案

这是由 SplPriorityQueue::compare() 决定的。文档说明了它的返回值:

Result of the comparison, positive integer if priority1 is greater than priority2, 0 if they are equal, negative integer otherwise.

Note:

Multiple elements with the same priority will get dequeued in no particular order.

请注意,参数 priority1priority2 声明为 mixed并且没有提到转换为 int。

这意味着 > 的通常规则应用(see comparison operator documentation):

  • 字符串与字符串比较:词法比较(如果两个字符串都是数字,则为数字)
  • int 与 int 比较:数值比较
  • string与int比较:字符串转换为数字,数值比较

(int)'a'(int)'b'解析为 0 ,这就是为什么这些项目排在所有数字之后的原因。

这些是您的示例的相关比较:

php > var_dump(1 > 'a');
bool(true)
php > var_dump(1 > 'b');
bool(true)
php > var_dump('b' > 'a');
bool(true)

关于php - 当优先级不是整数时,SplPriorityQueue 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15851726/

相关文章:

javascript - Onchange 无法使用 2 个选项

php - PHP 中从多维数组获取平面数组的内置方法

php - MySQL PDO 不在查询中

php - SPL 自动加载和命名空间

php - 通过 ArrayAccess 访问多维数组

php - 使用 PHP 添加 MySQL 中不存在的字段

php - 当我使用 (if,BEGIN,END) 时,sql 查询不起作用

php - 对非数组使用 OutOfBoundsException

php - PHP 的 SplDoublyLinkedList 类,更重要的是,一般的链表有什么意义?