gpt4 book ai didi

javascript - 将 PHP 数组回显到 Javascript

转载 作者:行者123 更新时间:2023-11-28 07:38:47 25 4
gpt4 key购买 nike

我目前正在开发一个项目,需要从数据库获取数据并将其生成为 Javascript 数组。它动态地改变图表。

我有以下 PHP 代码来获取数组。

<?php
ini_set('memory_limit', '1024M');
$dbconn = pg_connect(**My connection details**)
or die('Could not connect: ' . pg_last_error());

$county1 = $_GET['c1'];
$county2 = $_GET['c2'];
$county3 = "National";

$counties = 'SELECT * FROM house_price_data_db.county_median_months where county=$1 or county=$2 or county=$3 order by county';
$result_counties = pg_query_params($dbconn,$counties,array($county1,$county2,$county3)) or die('Query failed: ' . pg_last_error());
$county_meds = array();

while($r = pg_fetch_assoc($result_counties)) {
$county_meds[] = $r;
}
echo("var county_med_month=".json_encode(array_values($county_meds), JSON_NUMERIC_CHECK).";");

pg_free_result($result_counties);
pg_close($dbconn);
?>

运行时确实返回数组。

E.g
var county_med_month=[
{"county":"Carlow","med_jan_10":165000,"med_feb_10":170000,...,"med_dec_14":null}
{"county":"Dublin","med_jan_10":285000,"med_feb_10":280000,...,"med_dec_14":null},
{"county":"National","med_jan_10":220264.31,"med_feb_10":216500,...,"med_dec_14":null}];

但是由于某些原因,当我尝试在 Javascript 代码中使用数组时,它似乎不起作用?

function county_med_chart(){
county_1=document.getElementById("dd1_c").value;
county_2=document.getElementById("dd2_c").value;
var c;
county_meds(county_1,county_2);
for(c=0;c<county_med_month.length;c+=1){
var a=county_med_month.c;
if(a.county==county_1){
med_jan_10_1=parseFloat(a.med_jan_10);
:
med_sep_14_1=parseFloat(a.med_sep_14);
}
else if(a.county==county_2){
med_jan_10_2=parseFloat(a.med_jan_10);
:
med_sep_14_2=parseFloat(a.med_sep_14);
}
else if(a.county=="National"){
med_jan_10_3=parseFloat(a.med_jan_10);
:
med_sep_14_3=parseFloat(a.med_sep_14);
}
}

var e=new google.visualization.arrayToDataTable([
["Year",county_1,county_2,"National"],
["Jan-10",med_jan_10_1,med_jan_10_2,med_jan_10_3],
["Feb-10",med_feb_10_1,med_feb_10_2,med_feb_10_3],
:
["Aug-14",med_aug_14_1,med_aug_14_2,med_aug_14_3],
["Sept-14",med_sep_14_1,med_sep_14_2,med_sep_14_3],
]);

var b={
title:"House Price Index by County:",
curveType:"function",
is3D:true,
legend:"top",
width:650,
height:280,
hAxis: { textPosition: 'none' }};
var d=new google.visualization.LineChart(document.getElementById("chart_div"));
d.draw(e,b)
}

有什么建议吗?

最佳答案

为什么在使用代码执行任何复杂的逻辑之前不尝试调试代码?

在回显数组后,请在 javascript 顶部尝试以下操作:

if(county_med_month.length > 0) 
console.log("The array was created!, the problem was with my JavaScript code!");

顺便说一句,您不访问带有点表示法的数组值

var a=county_med_month.c;

应该是红色的

var a=county_med_month[c];

关于javascript - 将 PHP 数组回显到 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com