<?xml version="1.0" encoding="windows-1252"?>
<node id="377672" title="Solution - Re: Building an index for next/last in a photo album." created="2004-07-27 03:14:54" updated="2005-06-08 10:23:47">
<type id="11">
note</type>
<author id="5565">
Seumas</author>
<data>
<field name="doctext">
This is the solution I put together. I'm not sure how speedy it is in relation to the other suggestions in this thread, but as long as no album has more than a few thousand images, I suspect this method should be the fastest solution.
&lt;br&gt;&lt;br&gt;
If anyone has further ideas to tighten this up or yet other alternative approaches, I'm eager for you to share them with me.
&lt;br&gt;
&lt;code&gt;
# Elsewhere in the code, we get an img_id, do a SELECT to find what
# album_id it belongs to, then use the SELECT below to get all of
# the img_id's that belong to that album. We use flattenArray() to 
# turn the arrayref from DBI into a plain old array.
my @image_idx = flattenArray( @{$dbh-&gt;selectall_arrayref("SELECT img_id FROM images WHERE album_id = $image_id")});

# Find what place our target img_id is in the array.
my $idx_loc = indexArray($img_id, @image_idx);

# Get img_id's from array that come before and after the target.
my $prev_img = $image_idx[$idx_loc - 1];
my $next_img = $image_idx[$idx_loc + 1];

# Thanks to merlyn, tilly and particle
# http://perlmonks.org/index.pl?node_id=151120
sub flattenArray {
  my @flattened; # Will be in reverse order
  while (@_) {
    my $last = pop;
    if (UNIVERSAL::isa($last, "ARRAY")) { push @_, @$last; }
    else { push @flattened, $last; }
  }
  return reverse @flattened;
}

# My apologies, but I took this from a golf thread on PM. I've lost
# the node number and apologize to the author. Please let me know
# so I can credit you for this.
sub indexArray(@) {        
    my $s=shift;
    $_ eq $s &amp;&amp; return @_ while $_=pop;
    -1;
}
&lt;/code&gt;


</field>
<field name="root_node">
377548</field>
<field name="parent_node">
377548</field>
</data>
</node>
