http://www.perlmonks.org?node_id=377672


in reply to Building an index for next/last in a photo album.

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.

If anyone has further ideas to tighten this up or yet other alternative approaches, I'm eager for you to share them with me.
# 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->selectall_arrayref("SELECT img_i +d 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 && return @_ while $_=pop; -1; }