开发者

Rails HTML output for a table

开发者 https://www.devze.com 2023-04-05 19:49 出处:网络
I\'m having a tough time figuring out how to make a helper for my array that outputs an html table, here is what my array looks like.

I'm having a tough time figuring out how to make a helper for my array that outputs an html table, here is what my array looks like.

[
  {"day"=>1.0, "hour"=>14.0, "count"=>818.0},
  {"day"=>1.0, "hour"=>15.0, "count"=>366.0},
  {"day"=>1.0, "hour"=>16.0, "count"=>1246.0},
  {"day"=>1.0, "hour"=>17.0, "count"=>116.0},
  {"day"=>1.0, "hour"=>18.0, "count"=>434.0},
  {"day"=>1.0, "hour"=>19.0, "count"=>123.0},
  {"day"=>1.0, "hour"=>20.0, "count"=>442.0},
]

Additionally this is what my table should look like, how can I for each day output its name in the header, then for each hour of each hour of each day output the count value from my hash? I'm having a hard time picturing how to iterate over these values.

<table>
  <tr>
    <th style="width:8em"></th>
    <th>Monday</th>
    <th>Tuesday</th>
    <th>Wednesday</th>
    <th>Thursday</th>
    <th>Friday</th>
    <th>Saturday</th>
    <th>Sunday</th>
  </tr>

  <tr>
    <th scope="row">00:00–01:00</th>
    <td>468</td>
    <td>2721</td>
    <td>848</td>
    <td>3127</td>
    <td>803</td>
    <td>1970</td>
    <td>2673</td>
  </tr>

  <tr>
    <th scope="row">01:00–02:00</th>
    <td>468</td>
    <td>2721</td>
    <td>848</td>
    <td>3127</td>
    <td>803</td>
    <td>1970</td>
    <td>2673</td>
  </tr>

  <!-- remaining hours of the day for each day continue... -->

</table>

Any help at all would be re开发者_运维百科ally really appreciated.


Your data doesn't match what you want to do with it, so the first step is to transform your data. This snippet of code is pretty ugly, but it will do the trick:

# arr holds your original array of hashes
by_hour = arr.group_by { |x| x["hour"] }
by_hour.each do |k, v|
  v.sort! { |a,b| a["day"] <=> b["day"] }.map! { |x| x["count"] }
end

by_hour now looks like:

{20.0=>[442.0],
 19.0=>[123.0],
 14.0=>[818.0],
 18.0=>[434.0],
 17.0=>[116.0],
 15.0=>[366.0],
 16.0=>[1246.0]}

where the array holds the counts for each day of the week (from Monday to Sunday, assuming Sunday is 7.0.

From here it should be trivial to build your table. Something like:

<% by_hour.keys.sort.each do |hour| %>
  <tr>
    <% by_hour[hour].each do |count| %>
      <td><%= count %></td>
    <% end %>
  </tr>
<% end %>
0

精彩评论

暂无评论...
验证码 换一张
取 消