published on in HowTo
tags: php

SplMaxHeap aka SelfSort-“array”

SplMaxHeap is useful ;)

<?php
class MyListHeap extends SplMaxHeap {
  public function compare( $value1, $value2 ) {
    return ( $value1['created_at'] - $value2['created_at'] );
  }
}

$list = new MyListHeap;

$list->insert(array('user_id' => 1, 'created_at' => time()-2000));
$list->insert(array('user_id' => 2, 'created_at' => time()-1000));
$list->insert(array('user_id' => 3, 'created_at' => time()-5000));

foreach($list as $l) {
  echo "{$l['user_id']}:{$l['created_at']}\n";
}

And the output will be:

2:1309908000
1:1309907000
3:1309904000

And the output will be:

2:1309908000
1:1309907000
3:1309904000

Read more: https://hu2.php.net/splmaxheap