Itérer dans un tableau PHP dans jQuery?
Question
Comment parcourir un tableau PHP dans jQuery? J'ai un tableau en php nommé $ viewfields
.
Comment parcourir chaque élément de ce tableau à l'aide de jQuery?
MODIFIER 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'];?>");
}
Si je donne
$.each(arrayfromPHP,function(i,elem){
}
comment puis-je écrire le code pour $ view ['Attribute'] ['type'] dans jQuery? elem ['Attribute'] ['type'] ne fonctionnera pas, je suppose?
EDIT 2
elem ['Attribute'] ['type'] fonctionne
La solution
var arrayFromPHP = <?php echo json_encode($viewFields) ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
Pour mieux comprendre comment les choses sont connectées (merci 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>
Vous pouvez bien sûr placer cette balise SCRIPT
où vous voulez dans la page, ou même référencer arrayFromPHP
à partir de scripts externes sous la forme arrayFromPHP
est déclaré comme global.
EDIT
Étant donné ce tableau PHP:
$viewFields = array(
'Attributes' => array(
'type' => 'foo',
'label' => 'bar',
),
'Attributes' => array(
'type' => 'foo',
'label' => 'bar',
),
);
Pour accéder à ses éléments avec jQuery, procédez comme suit:
// json_encode() will output:
// {"Attributes":{"type":"foo","label":"bar"}}
$.each(arrayFromPHP, function (i, elem) {
alert(elem.type);
alert(elem.label);
});
Autres conseils
Le moyen le plus simple est:
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);
});