在jQuery中遍历PHP数组?

15
我该如何在jQuery中遍历PHP数组?我有一个名为$viewfields的PHP数组。我该如何使用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'];?>");
}

如果我提供 <\p>
$.each(arrayfromPHP,function(i,elem){

}

我该如何用jQuery编写代码来获取$view['Attribute']['type']的值?elem['Attribute']['type']不能起作用,对吧? 修改2 elem['Attribute']['type'] 确实有效。
2个回答

44
var arrayFromPHP = <?php echo json_encode($viewFields) ?>;

$.each(arrayFromPHP, function (i, elem) {
    // do your stuff
});
为了更好地理解事物如何连接在一起(感谢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被声明为全局变量。

编辑

给定此PHP数组:

$viewFields = array(
    'Attributes' => array(
        'type'  => 'foo',
        'label' => 'bar',
    ),
    'Attributes' => array(
        'type'  => 'foo',
        'label' => 'bar',
    ),
);

使用jQuery访问它的元素应该这样做:

// json_encode() will output:
// {"Attributes":{"type":"foo","label":"bar"}}

$.each(arrayFromPHP, function (i, elem) {
    alert(elem.type);
    alert(elem.label);
});

1
请注意,PHP和jQuery不是并排编写的。您需要将PHP包装在<?php和?>中,将jQuery包装在<script type="text/javascript">和</script>中。 - Sampson
在 PHP 的数组中,我使用数组的各个元素,例如 $view['Attribute']['id'] 或 $view['Attribute']['label'],其中我将 $view 分配为 <?php foreach($viewfields as $view):?>。如何在 .each 函数() 中访问这些元素? - Angeline
@Angeline,你能否编辑问题并发布PHP数组的结构,就像print_r返回的那样?只需粘贴print_r($viewFields)的输出即可。 - Ionuț G. Stan
顺便提一下,这里有关于jQuery.each的一些文档:http://docs.jquery.com/Utilities/jQuery.each - Ionuț G. Stan
@lonut G.Stan:非常感谢。我已经得到了答案。 但是有一个小改变,应该是elem ['Attribute'] ['type']而不是elem.type。;) - Angeline

-2

最简单的方法是:

PHP:

$an_array=array();
$an_array[]='Element 1';
$an_array[]='Element 2';
$an_array[]='Element 3';
$array_js=implode(",",$this->js_pagina); //join elements in a string

JQUERY:

//Converter
window.array=new String('<?php echo $array_js?>');
window.array=window.js_pagina.split(",");
//Iterator
$.each(window.array, function (i, elem) 
{
        alert(elem);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接