我正在使用一个内部带有foreach循环的for循环。在foreach循环中,我获取了我需要的信息并将其回显到如下所示的字符串中:19:00^-2,2° C
。我想把时间(19:00
)放在一个变量中,把温度(-2,2° C
)放在另一个变量中,这样我就可以把它们用在图表上。但我不知道我该如何拼接这两者。这是它目前的样子:
var yr = localStorage.yr.split('|');
time = yr[16].split('~');
temp = time.split('^');
lineChartData = {
labels: time,
datasets: [{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: temp
}]
}
有了这段代码,我Uncaught TypeError: undefined is not a function
temp = time.split('^');
. yr[16]
打印以下内容:
19:00^-2,2° C~20:00^-2° C~21:00^-2° C~22:00^-1,9° C~23:00^-1,6° C~00:00^-1,5° C~01:00^-1,3° C~02:00^-1,1° C~03:00^-0,9° C~04:00^-0,9° C~05:00^-1,1° C~06:00^-1,3° C~07:00^-1,6° C~
PHP代码如下所示:
for($i = 0; $i < 13; $i++) {
$datetime = date('Y-m-d'TH', strtotime('+'.$i.' hour'));
$forecast_period = $forecast->xpath('(//product/time[contains(@datatype, "forecast")][contains(@from, "'.$datetime.':00:00Z")][contains(@to, "'.$datetime.':00:00Z")])');
foreach($forecast_period AS $period) {
$period_datetime = date('H:i', strtotime($period->attributes()->from));
$period_temperature = $period->location->temperature->attributes()->value;
$period_temperature_dewpoint = $period->location->dewpointTemperature->attributes()->value;
$period_temperature_unit = $period->location->temperature->attributes()->unit;
$period_wind_direction = $period->location->windDirection->attributes()->name;
$period_wind_direction_degrees = $period->location->windDirection->attributes()->deg;
$period_wind_speed = $period->location->windSpeed->attributes()->mps;
$period_fog = $period->location->fog->attributes()->percent;
$period_cloudiness = $period->location->cloudiness->attributes()->percent;
$period_cloudiness_low = $period->location->lowClouds->attributes()->percent;
$period_cloudiness_medium = $period->location->mediumClouds->attributes()->percent;
$period_cloudiness_high = $period->location->highClouds->attributes()->percent;
$period_pressure = $period->location->pressure->attributes()->value;
$period_pressure_unit = $period->location->pressure->attributes()->unit;
$period_humidity = $period->location->humidity->attributes()->value;
echo $period_datetime.'^'.temp($period_temperature, $period_temperature_unit, 'not-normal').'~';
}
}
我通过 simplexml_load_file()
从 YR 的 API 获取信息($forecast
是使用 simplexml_load_file()
从 API 获取 XML 数据的人)。
话虽如此,这是我的问题:如何将yr[16]
的时间和温度放入两个变量而不会出错,从而构建图表?
您可以使用Array.prototype.map
:
var time_and_temp = time.map(function(el) {
var temp = el.split('^');
return { time: temp[0], temperature: temp[1] };
});
这会将time_and_temp
设置为如下数组:
[ { time: "19:00",
temperature: "-2,2° C"
},
{ time: "20:00",
temperature: "-2° C"
}
...
]
yr16 = yr[16].toString();
time = yr16.split('^')[0];
temp = yr16.split('^')[1];
您需要在.split('^')
后包含[0]
和[1]
,以指示哪个部分(在^
之前或之后)被分配给变量。