在 jQuery 中遍历 PHP 数组? [英] Iterating through a PHP array in jQuery?
问题描述
如何在 jQuery 中遍历 PHP 数组?我在 php 中有一个名为 $viewfields
的数组.如何使用 jQuery 遍历此数组的每个元素?
How do I iterate through a PHP array in jQuery? I have an array in php named $viewfields
.
How do I iterate through each element of this array using jQuery?
编辑 1
<?php foreach ($viewfields as $view): ?>
if(<?=$view['Attribute']['type'];?>=='text'||<?=$view['Attribute']['type'];?>=='number')
{
$("<input id=input<?=$view['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$view['Attribute']['size'];?>px' data-attr=<?=$view['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$view['Attribute']['sequence_no'];?>");
}
如果我给
$.each(arrayfromPHP,function(i,elem){
}
如何在 jQuery 中编写 $view['Attribute']['type'] 的代码?elem['Attribute']['type'] 不会工作吧?
how do I write the code for $view['Attribute']['type'] in jQuery? elem['Attribute']['type'] won't work I suppose?
编辑 2
elem['Attribute']['type'] 确实有效
elem['Attribute']['type'] does work
推荐答案
var arrayFromPHP = <?php echo json_encode($viewFields) ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
为了更好地理解事物是如何联系在一起的(感谢乔纳森·桑普森):
To better understand how the things are wired together (thanks Jonathan Sampson):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var arrayFromPHP = <?php echo json_encode($viewFields) ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
</script>
</head>
<body>
</body>
</html>
您当然可以将 SCRIPT
标签放置在页面中任何您想要的位置,或者您甚至可以从外部脚本中将 arrayFromPHP
引用为 arrayFromPHP
被声明为全局.
You can of course place that SCRIPT
tag wherever you want in the page, or you can even reference arrayFromPHP
from external scripts as arrayFromPHP
is declared as global.
给定这个 PHP 数组:
Given this PHP array:
$viewFields = array(
'Attributes' => array(
'type' => 'foo',
'label' => 'bar',
),
'Attributes' => array(
'type' => 'foo',
'label' => 'bar',
),
);
使用 jQuery 访问它的元素是这样完成的:
Accessing its elements with jQuery would be done like this:
// json_encode() will output:
// {"Attributes":{"type":"foo","label":"bar"}}
$.each(arrayFromPHP, function (i, elem) {
alert(elem.type);
alert(elem.label);
});
这篇关于在 jQuery 中遍历 PHP 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!