[英]PHP Array into JS Array
诚然,我对数组的理解只是初级(尽管在此之前我以为我已经弄清楚了)。
本质上,我正在尝试将PHP数组转换为JS数组。 这样做的目的是最终我想使用jquery创建一个图形/图表(我已经尝试过使用php图表,但是到目前为止,它们对我来说还没有用)。
长话短说,每次我尝试将PHP数组转换为JS数组时,输出均为“ null”。 这可能是由于我对数组的理解...
//this query gets me the count of each type of variabletype
$sql = "SELECT variabletype, COUNT(variabletype) AS value_occurrence FROM variable GROUP BY variabletype ORDER BY value_occurrence DESC";
$vars_query = mysqli_query($con,$sql) or die(mysqli_error($con));
while($vars = mysqli_fetch_array($vars_query, MYSQLI_ASSOC))
{
//this is a sub-query that gets me how many of those records are considered "positive"
$times_positive_qry = mysqli_query($con, "SELECT variable.variabletype, COUNT(value.valueid) AS positive_occurrence FROM variable INNER JOIN value On variable.variableid=value.variableid WHERE variable.variabletype = '" .$vars['variabletype']. "' AND value.valuelift>0.00 AND value.valuesignificant=1 GROUP BY variable.variabletype ORDER BY positive_occurrence DESC");
$times_positive = mysqli_fetch_array($times_positive_qry, MYSQLI_ASSOC);
$pos = $times_positive['positive_occurrence'];
}
//this is the code that is supposed to take my php array and turn it into JS array.
echo "<script type='text/javascript'>";
$php_array = $pos;
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
echo "</script>";
同样,我对数组的理解还很初级,但是我认为这可能与$ pos的使用有关。 这不是数组吗? 还是我在其他地方缺少商标?
任何帮助将非常感激!
您可以将$ pos明确声明为如下数组:
$pos = array();
在while循环内,可以使用如下方括号来确保它是一个数组,并且在循环遍历时不会丢失数据:
$pos[] = $times_positive['positive_occurrence'];
该语法会自动创建一个索引数组。 如果不使用该语法,则$ pos的值将只是在while语句的最终循环中分配的值。
您有这行:
$pos = $times_positive['positive_occurrence'];
它为变量$pos
赋值。 您分配的值可能不是数组,但除此之外,您每次循环都覆盖$ pos。
因此,我认为您打算这样做:
$pos[] = $times_positive['positive_occurrence'];
这会将$pos
视为一个数组,并将每个新值附加到该数组的末尾。
您可能需要编写$pos = array();
来启动脚本$pos = array();
。 这样,您可以确保$ pos已经存在并且是有效的(空)数组,以防查询不返回任何结果。
这可能是您想要的解决方案。
和您的JavaScript看起来像这样:
<script type='text/javascript'>
<?php
//this is just and example you can replace it with $pos[]
$php_array = array('abc','def','ghi');
?>
var js_array =<?php echo json_encode($php_array);?>;//do not add quotes to this line
alert(js_array[0]);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.