[dancer-users] list order from a hash
Andrew Beverley
andy at andybev.com
Wed Aug 26 15:04:25 BST 2015
On Wed, 2015-08-26 at 08:51 -0500, Richard Reina wrote:
> I have this table data that I load into a template as follows.
>
> $q = "SELECT ID, NAME
> FROM jobs
> ORDER BY NAME";
> $sth = $dbh->prepare($q);
> $sth->execute();
> my $Jobs_ref = $sth->fetchall_hashref('ID');
use fetchall_arrayref() instead.
> To display it in the template as a drop-down select I do:
>
> <select class="selectpicker" name="jobselect" id="jobselect"
> style="width: 500px;">
> <% FOREACH ID IN Jobs.keys %>
Here you just need something like
FOREACH job in Jobs
> <option value="<% Jobs.$ID.ID %>"><% Jobs.$ID.NAME %></option>
And then here use job.ID, job.NAME etc.
> And it works great. Except for one thing, the list is not in order by name.
> I have read more than a few posts about how once you save a query as a
> hashref that the order is lost.
Yes, in Perl arrays are ordered, hashes are not. If you want to retain order, you
must use an array (or sort the hash before use, which is expensive).
> Most of those posts suggested fetching as a
> arrayref instead. However, I have no idea how to do that and then display
> it in a select like the above code does.
See above.
More information about the dancer-users
mailing list