如何在jQuery中迭代PHP数组?我在PHP中有一个名为 $ viewfields 的数组。 如何使用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']不起作用?

编辑2

elem ['Attribute'] ['type']有效

有帮助吗?

解决方案

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);
});

其他提示

简单方法是:

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);
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top