在js中组合两个数组或使用其他数据格式的highcharts

时间:2014-11-20 13:11:45

标签: json sqlite highcharts

我有一个带有这样的表的sqlite数据库: 1次 2. cpu 记忆 4. ...

我想将所有这些值放在Highstock Chart上,时间将是我的xAsis。我有一个cgi脚本,它以格式返回数据 [[time1,time2,time3],[cpu1,cpu2,...],[mem1,mem2 ...]]

据我所知,Highcharts希望每个系列的数据都像[[time1,cpu1],[time2,cpu2]]。有没有办法将我的格式的值组合成这种格式?像matrix = [time [],cpu []]

之类的东西

我尝试在循环中重写它们,但是对于大量数据来说这是个糟糕的想法。 (在这种情况下,这样的循环是不可能的(性能问题)因为数据库中的新点和延迟加载,图表将每1-2秒更新一次 - 如上所述:here)。

我对以[[time1,cpu1],[time2,cpu2]]格式发送数据持怀疑态度,因为IMO会非常沉重。如果我错了,请纠正我。而现在我真的不知道该怎么做。

我的sqlite-> json的cgi脚本:

#!/bin/bash

echo Content-type: text/plain
echo

#sqlite3 to json
#playing with field separators to get params working
OIFS="$IFS"
IFS="${IFS}&"
set $QUERY_STRING
Args="$*"
IFS="$OIFS"


# params:
# 1 - start (int)
# 2 - end (int)
TIMESTART="$1"
shift
TIMEEND="$1"

if [[ $TIMESTART =~ ^[0-9]+$ ]] && [[ $TIMEEND =~ ^[0-9]+$ ]]; then
    echo "["
    echo -en "[";  sqlite3 /home/moonitor/moonitor-misc/data/cpu.db "select time from usage_cpu where time between '$TIMESTART' and '$TIMEEND' " | tr '|' ',' | sed -e ':a;N;$!ba;s/\n/, /g' ; echo "],"
    echo -en "[";  sqlite3 /home/moonitor/moonitor-misc/data/cpu.db "select time, summary from usage_cpu where time between '$TIMESTART' and '$TIMEEND'" | tr '|' ',' | sed -e ':a;N;$!ba;s/\n/, /g' ; echo "],"
    echo -en "[";  sqlite3 /home/moonitor/moonitor-miscd/ata/cpu.db "select time, user from usage_cpu where time between '$TIMESTART' and '$TIMEEND'" | tr '|' ',' | sed -e ':a;N;$!ba;s/\n/, /g' ; echo "],"
    echo -en "[";  sqlite3 /home/moonitor/moonitor-misc/data/cpu.db "select time, nice from usage_cpu where time between '$TIMESTART' and '$TIMEEND'" | tr '|' ',' | sed -e ':a;N;$!ba;s/\n/, /g' ; echo "],"
    echo -en "[";  sqlite3 /home/moonitor/moonitor-misc/data/cpu.db "select time, kernel from usage_cpu where time between '$TIMESTART' and '$TIMEEND'" | tr '|' ',' | sed -e ':a;N;$!ba;s/\n/, /g' ; echo "]"
    echo "]"
fi

1 个答案:

答案 0 :(得分:0)

你是对的,就用户< - >服务器之间的通信而言,最好只附加一次时间戳。您仍然可以这样做,然后只需转换您的数据格式以符合Highcharts要求,简单的代码段:

function convertData(data) {
  var s = [{
    name: 'cpu',
    data: []
  },{
    name: 'nice',
    data: []
  },{
    name: 'test',
    data: []
  }]; //create series array for chart


  // append points
  $.each(data, function(i, vals) {
    s[0].data.push([ vals[0], vals[1] ]);
    s[1].data.push([ vals[0], vals[2] ]);
    s[2].data.push([ vals[0], vals[3] ]);        
  });

  return s;
}

现场演示:http://jsfiddle.net/Ywr3L/43/

注意:我使用固定数量的点(三个系列)。如果您不知道有多少可用,最好在另一个循环中创建系列。