Jeremy Kister <mailto:[EMAIL PROTECTED]> wrote:

: I'm stumped on how to sort an array based on a hash refrences's
: key in each element of my array.
:
: this is dumbed down code of what I have:
: my @array;
: while(my $row = $sth->fetchrow_arrayref){

:  my %hash = (id => $row->[0], name => $row->[1]);
:  push(@array, \%hash);

    No need for %hash.

push @array, {
        id   => $row->[0],
        name => $row->[1],
    };


: }
:
: after the while loop, I'm trying to build a new version of
: @array, sorted by the 'name' key.

    This might do.

my @sorted_array;
if ( @array) {
    @sorted_array = sort { $a->{name} cmp $b->{name} } @array;

} else {
    # Houston, we have a problem.
}


    Q: Why use fetchrow_arrayref()? In fact, why sort with perl?

    If you structure your query to return the first column "AS id"
the second column "AS name", with an "ORDER BY name" clause, you
could just use this to build the sorted array.

my @array;
while ( my $row = $sth->fetchrow_hashref() ) {
    push @array, $row;
}


HTH,


Charles K. Clarkson
--
Mobile Homes Specialist
254 968-8328


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to