我在数据库中有一个表,数据库中有三列prop_no
、prop_name
和prop_sc
,我将最后两列的条目移动到两个PHP数组$propertyNameList
和$propertyCodeList
中。现在我有了一个JavaScript类Property
和一个数组propList
。我需要使用将两个PHP数组中的所有值移动到这个JS数组中
propList.push(new Property(1,<?php echo json_encode($propertyNameList[0]); ?>,
<?php echo json_encode($propertyCodeList[0]); ?>));
使用for循环,其中第一个参数将是计数器变量,PHP数组索引必须随每次迭代而更改。我该怎么做?
我可能建议您稍微重组一下,但使用临时并行数组可以很容易地做到这一点。
在这里,我们将这些并行数组转储到客户端代码,然后在JavaScript:中进行循环
(function() {
var names = <?php echo json_encode($propertyNameList) ?>;
var codes = <?php echojson_encode($propertyCodeList) ?>;
for (var n = 0; n < names.length; ++n) {
propList.push(new Property(names[n], codes[n]));
}
})();
或者,如果您更喜欢PHP端的循环:
<?php
$index = 0;
for ($index = 0; $index < count($propertyNameList); ++$index) {
echo 'propList.push(new Property(' . json_encode($propNameList[$index]) . ', ' . json_encode($propCodeList[$index]) . '));';
}
?>
(我认为,我的PHP相当弱。)