将数组索引号从 PHP 传递到 Javascript

Passing Array Index numbers from PHP to Javascript

JS 新手和 PHP 并修改幻灯片脚本以动态显示三个不同目录的内容。几乎让事情从一开始就很简单。

我遇到的一个问题是我正在修改的脚本使用以下静态代码来填充 javascript 数组:

variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']
variableslide[2]=['team_a/futuristic.jpg']
variableslide[3]=['team_a/lambo.jpg']

我的 PHP 代码目前可以动态枚举目录,然后将结果传递给 Javascript:

<?php

// Header("content-type: application/x-javascript"); 

$team_a = array();
$team_b = array();
$team_c = array();
foreach (new DirectoryIterator('team_a') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_a[] = "team_a".'/'.$fileInfo->getFilename();
}

foreach (new DirectoryIterator('team_b/') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_b[] = $fileInfo->getFilename();
}

foreach (new DirectoryIterator('team_c') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_c[] = $fileInfo->getFilename();
}

?>
<script type="text/javascript">

var variableslide = <?php echo json_encode($team_a, JSON_UNESCAPED_SLASHES)
?>

当我在 Chrome 中 "inspect element" 而 运行 完整代码时,我可以看到文件名正在传递给 Javascript,但是缺少 0 ,1,2,3,4 等。我只得到文件路径。结果如下:

var variableslide =     ["team_a/blank.jpg","team_a/ford.jpg","team_a/futuristic.jpg","team_a/lambo.jpg"];

我一直在谷歌搜索的是如何让 var variableslide 数组这样读取:

variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']

从PHP中提取数组索引号和文件名,并在 JS 中填充变量幻灯片数组,使其读取与上面相同。当我从 PHP 脚本 print_r 时,它会正确显示索引号和文本。谁能帮我解决这个问题!谢谢!

if you wont it to look like this

variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']

in the php file use

<script type="text/javascript">

<?php
foreach($team_a as $i=>$v){ echo 'variableslide['.$i.']="'.$v.'";'."\n";}
?>

insetad of

<script type="text/javascript">

var variableslide = <?php echo json_encode($team_a, JSON_UNESCAPED_SLASHES)
?>

* ***请注意,这是完全相同的事情!*