It's useful trick in situation when you need to sort certain groups of data. Preserve chronological order of items inserted in Heap.
Good use-case is php_error_log.
Each log entry has own majority of error. And it's usefull to sort file using max heap.
The soulution is - override default SplPriorityQueue
<?php
class OrderedPriority extends SplPriorityQueue
{
protected $serial = PHP_INT_MAX;
public function insert($value, $priority)
{
parent::insert($value, array($priority, $this->serial--));
}
}
function setPriority($line) {
$start = strpos($line, 'PHP');
$end = strpos($line, ':', $start);
$error = substr($line, $start, $end-$start);
switch ($error) {
case 'PHP Fatal error':
case 'PHP Catchable fatal error':
return 10;
case 'PHP Warning':
return 8;
case 'PHP Deprecated':
return 7;
case 'PHP Parse error':
return 5;
case 'PHP Notice':
return 2;
default:
return 0;
}
}
$log = new OrderedPriority(); // SplPriorityQueue can be here, but then we'll lose chronolocial order
$file = new SplFileObject('php_error_log');
while (!$file->eof()) {
$line = $file->fgets();
$log->insert($line, setPriority($line));
}
while (!$log->isEmpty()) {
echo $log->extract() . '<br>';
}