简体   繁体   English

我们如何将数组的单个值分配给javascript中的任何变量

[英]how we can assign single value of array to any variable in javascript

<?php
$abc=array();
$abc = (abc, cde,fre);
?>
<script language="javascript" type="text/javascript">
for (var i = 0; i < 3; i++) {
var gdf = "<?php echo $lat['i'];?>";
alert("value ="+gdf);
}
</script>

You're not looking to assign a single value of the array; 您不想分配数组的单个值; you're looking for the whole array. 您正在寻找整个阵列。 Your JavaScript loop is trying to iterate over the entire $abc array from PHP. 您的JavaScript循环正在尝试从PHP遍历整个$abc数组。

Something like this would work: 这样的事情会起作用:

var abc = <?php echo json_encode($abc); ?>;
for(var i = 0; i < 3; i++)
    var gdf = abc[i];
    alert("value = " + gdf);
}

Firstly, to build a PHP array you should be using this notation: 首先,要构建一个PHP数组,您应该使用以下符号:

<?php

$abc = array('abc', 'cde', 'fre');

?>

Next, it's not possible use JavaScript to directly loop through your variable that is stored in PHP. 接下来,不可能使用JavaScript直接循环浏览存储在PHP中的变量。 You can do something like this instead, performing the loop in PHP: 您可以改为执行以下操作,在PHP中执行循环:

<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
    <?php foreach ( $abc as $el ): ?>
    alert('value=<?php echo $el ?>');
    <?php endforeach ?>
</script>

Or, if you'd really like the loop to happen in JavaScript and not PHP, you can "export" the PHP array to JavaScript by converting the array to a JSON string and outputting it. 或者,如果您真的希望循环在JavaScript中发生而不是在PHP中发生,则可以通过将数组转换为JSON字符串并输出来将PHP数组“导出”到JavaScript。

<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
    var abc = <?php echo json_encode($abc) ?>;

    for ( var i = 0; i < abc.length; i++ ) {
        alert('value=' + abc[i]);
    }
</script>

Following your comment, I think this is what you are trying to do: 在您发表评论之后,我认为这是您想要做的:

<?php

$abc = array('abc', 'cde', 'fre');

?>
<script type="text/javascript">
var gdf = '<?php

for ($i = 0; $i < count($abc); $i++) {
    echo "{$abc[$i]}";
    if ($i != (count($abc)-1)) echo ", ";
}

?>';
</script>

Will output: 将输出:

http://codepad.org/KjEH5CmN http://codepad.org/KjEH5CmN

<script type="text/javascript">
var gdf = 'abc, cde, fre';
</script>

NOTE 注意

Using implode if you want a single variable would also work well: 如果需要单个变量,可以使用implode效果很好:

http://codepad.org/UwukCY4m http://codepad.org/UwukCY4m

<?php

$abc = array('abc', 'cde', 'fre');

?>
<script type="text/javascript">
var gdf = '<?php echo implode(', ',$abc); ?>';
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM