[英]How to access PHP array element using JavaScript variable as key?
So I am trying to make a simple academic system. 所以我试图建立一个简单的学术体系。 I made dynamic boxes which show course information.
我制作了动态框,显示课程信息。 Core code looks like this
核心代码看起来像这样
function addcourses(){ //(numcourses)
var num_courses= <?php echo $_GET['num']?>; //=numcourses
var newdiv;
var divIdName;
var i=0;
for(i=1;i<=num_courses;i++){
var divtoadd = document.getElementById('courselist');
newarticle = document.createElement('article');
divIdName = 'course'+i;
newarticle.setAttribute('id',divIdName);
newarticle.innerHTML ='<div class="box"><h2><?php echo $course_num_arr[i]?></h2><div class="content"><p>Credit Hours: <?php echo $credit_arr[0]?> </p><p>Professor: <?php echo $prof_arr[0]?></p><p>Average GPA: <?php echo $avg_arr[0]?></p><p>GPA: <?php echo $gpa_arr[0]?></p></div></div>';
call_course();
divtoadd.appendChild(newarticle);
}
}
The problem is with <?php echo $course_num_arr[i]?>
since i
is the variable from javascript, I don't know how to deal with this. 问题出在
<?php echo $course_num_arr[i]?>
因为i
是来自javascript的变量,我不知道如何处理这个问题。
I want to echo $course_num_arr[1]
when i = 1
and $course_num_arr[2]
when i = 2
and so on. 我想回声
$course_num_arr[1]
当i = 1
和$course_num_arr[2]
当i = 2
等。
If you don't want to use ajax call and wants to place the code in the PHP file, your can use json_encode()
function. 如果您不想使用ajax调用并希望将代码放在PHP文件中,则可以使用
json_encode()
函数。 Please refer below code. 请参考以下代码。
<?php
$cources = array( "0" => array ("name" => "maths","credits" => 30),"1"
=> array ("name" => "physics","credits" => 30));
?>
<script>
data=<?php echo json_encode($cources); ?>;
for(i=0;i<data.length;i++){
alert(data[i].name)
var h = document.createElement("H1");
var t = document.createTextNode(data[i].name);
h.appendChild(t);
document.body.appendChild(h);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.