Skip to content

Instantly share code, notes, and snippets.

@nash-ye
Last active August 29, 2015 13:56
Show Gist options
  • Save nash-ye/9230544 to your computer and use it in GitHub Desktop.
Save nash-ye/9230544 to your computer and use it in GitHub Desktop.
<?php
/**
* Priority Array
*
* @since 1.3
*/
class PriorityArray implements \IteratorAggregate, \ArrayAccess, \Serializable, \Countable {
/*** Properties ***********************************************************/
/**
* Elements List
*
* @var array
* @since 1.3
*/
protected $e6s = array();
/**
* Priorities List.
*
* @var array
* @since 1.3
*/
protected $p8s = array();
/**
* Is Sorted? (Flag)
*
* @var bool
* @since 1.3
*/
private $is_sorted = false;
/*** Methods **************************************************************/
/**
* @return void
* @since 1.3
*/
public function offsetSet( $index, $value, $priority = 10 ) {
$this->p8s[ $index ] = (int) $priority;
$this->e6s[ $index ] = $value;
$this->is_sorted = false;
}
/**
* @return bool
* @since 1.3
*/
public function offsetExists( $index ) {
return isset( $this->e6s[ $index ] );
}
/**
* @return void
* @since 1.3
*/
public function offsetUnset( $index ) {
unset( $this->p8s[ $index ] );
unset( $this->e6s[ $index ] );
}
/**
* @return mixed
* @since 1.3
*/
public function offsetGet( $index ) {
if ( $this->offsetExists( $index ) ) {
return $this->e6s[ $index ];
}
}
/**
* @return ArrayIterator
* @since 1.3
*/
public function getIterator() {
$this->maybeSort(); // Sort the array.
return new \ArrayIterator( $this->e6s );
}
/**
* @return void
* @since 1.3
*/
public function unserialize( $data ) {
$this->e6s = unserialize( $data );
}
/**
* @return string
* @since 1.3
*/
public function serialize() {
return serialize( $this->e6s );
}
/**
* @return bool
* @since 1.3
*/
public function maybeSort() {
if ( ! $this->is_sorted ) {
$p8s = (array) $this->p8s;
$this->is_sorted = uksort( $this->e6s,
function( $a, $b ) use ( &$p8s ) {
$p1 = (int) $p8s[ $a ];
$p2 = (int) $p8s[ $b ];
if ( $p1 === $p2 ) {
return 0;
}
return ( $p1 < $p2 ) ? +1 : -1;
}
);
}
return $this->is_sorted;
}
/**
* @return int
* @since 1.3
*/
public function count() {
return count( $this->e6s );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment