简体   繁体   中英

How to build two dimensional arrays from a query?

I have a query in Rails that's extracting 3 data points: data1, data2, and datetime. I need to assemble these into two different 2D arrays for insertion into a graph (Highcharts) such as this: http://jsfiddle.net/RKVgx/

You can see that the data will ultimately be used in the js like:

series: [{
    data: [[6, 540], [7, 540], [7, 1620], [8, 1620]]
},{
    data: [[6, 340], [7, 340], [7, 620], [8, 620]]
}]

By using lazy_high_charts this is pretty straight forward, however I simply need to compose the arrays appropriately for output. What I was thinking was something like this, but I need some help in building the 2D arrays properly for insertion:

readings = ModelName.order("date DESC").select('table_name.data1, table_name.data2, table_name.date').limit(1000).all

# HELP HERE, Need 2D arrays here...
data2_and_time_array = Array.new
data1_and_time_array = Array.new

readings.each do |row|
  # HELP HERE, build place datetime into each for X axis
  data1_and_time_array.push row[:date]
  data2_and_time_array.push row[:date]

  # These are the Y data points in each series
  data1_and_time_array.push row[:data2].to_f
  data2_and_time_array.push row[:data1].to_f

end


f.series(
    :name => 'Data1',
    # Date is X & must be first in each 2D array, I believe
    # in format of: [[X1, Y1], [X2, Y2], ... [Xn, Yn]]
    :data => data1_and_time_array 
)
f.series(
    :name => 'Data2',
    :data => data2_and_time_array
)

If you could provide the appropriate fixes / logic to do this correctly in the example code above, I'd much appreciate it.

Not sure i understand well what you want, but map should do the trick :

data2_and_time_array = readings.map{|row| [row.date, row.data1.to_f] }
data1_and_time_array = readings.map{|row| [row.date, row.data2.to_f] }

EDIT :

you can perform any processing you want inside the block :

data2_and_time_array = readings.map do{|row| [row.date, row.data1 == -1 ? row.data1.to_f : nil] } 

when performing complex processing, it is encouraged to use the do...end block syntax for a more readable code :

data2_and_time_array = readings.map do |row| 
  date, data = row.date, row.data1
  data = (data == -1) ? nil : data.to_f
  [date, data]
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM