Cleaning the Drupal Queue

Code to delete duplicate notifications in the queue

$notifications = db_select( 'queue', 'q' );
$notifications->addField( 'q', 'item_id', 'id' );
$notifications->addField( 'q', 'data', 'd' );
$notifications->where( 'q.name = \'sog_notifications_email\' OR q.name = \'sog_notifications_sms\'' );
 
$result = $notifications->execute();
 
$data = array();
 
while( $record = $result->fetchAssoc() ) {
	$row = unserialize( $record[ 'd' ] );
 
	$row[ 'id' ] = $record[ 'id' ];
 
	$data[ $record[ 'id' ] ] = $row;
}
 
$array = $data;
 
$stop = false;
 
while( !$stop ) {
	$deleted = 0;
 
	for ($e = 0; $e < count( $array ); $e++) {
		$duplicate = null;
 
		for ($ee = $e+1; $ee < count($array); $ee++) {
			if( strcmp($array[$ee]['value'],$array[$e]['value']) === 0 && 
				strcmp($array[$ee]['title'],$array[$e]['title']) === 0 &&
				$array[ $ee ][ 'type' ] == $array[ $e ][ 'type' ] &&
				$array[ $ee ][ 'target' ] == $array[ $e ][ 'target' ] &&
				strcmp($array[$ee]['bundle'],$array[$e]['bundle']) === 0  ) {
 
				$duplicate = $ee;
				break;
			}
		}
 
		if (!is_null($duplicate)) {
			db_delete( 'queue' )->condition( 'item_id', $array[ $ee ][ 'id' ] )->execute();
			$deleted++;
			array_splice($array,$duplicate,1);
		}
	}
 
	if( $deleted == 0 ) {
		$stop = true;
	}
}

Code to show the queue sorted by notification value

$notifications = db_select( 'queue', 'q' );
$notifications->addField( 'q', 'item_id', 'id' );
$notifications->addField( 'q', 'data', 'd' );
$notifications->where( 'q.name = \'sog_notifications_email\' OR q.name = \'sog_notifications_sms\'' );
$result = $notifications->execute();
 
$data = array();
 
while( $record = $result->fetchAssoc() ) {
	$row = unserialize( $record[ 'd' ] );
 
	$row[ 'id' ] = $record[ 'id' ];
 
	$data[ $record[ 'id' ] ] = $row;
 
}
 
usort( $data, 'sortfunc' );
 
function sortfunc( $a, $b ) {
	if( $a[ 'value' ] == $b[ 'value' ] ) {
		if( $a[ 'target' ] == $b[ 'target' ] ) {
			return 0;
		}
	} else if ( $a[ 'value' ] < $b[ 'value' ] ) {
		return -1;
	} else {
		return 1;
	}
}
 
$output = '';
 
for( $i = 0; $i < count( $data ); $i++ ) {
	dpm( $data[ $i ][ 'value' ] . ' -> ' . $data[ $i ][ 'target' ] . ' | ' . $data[ $i ][ 'type' ] );
}