Javascript json_编码($myVar);正在给映射,我想要一个字符串数组
我有以下HTML片段,使用PHP和JavaScript:Javascript json_编码($myVar);正在给映射,我想要一个字符串数组,javascript,php,Javascript,Php,我有以下HTML片段,使用PHP和JavaScript: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script> var imageIndex = 0; // index into imageNames array v
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
var imageIndex = 0; // index into imageNames array
var imageHeight = 400; // height of image; changed by user clicking size buttons
var imageNames; // names of images user can view in this album
function pageLoaded() // execute this when the page loads.
{
// PHP -- generate the array of image file names
<?php
function getImageNames($directory)
{
$handle = opendir($directory); // looking in the given directory
$file = readdir($handle); // get a handle on dir,
while ($file !== false) // then get names of files in dir
{
$files[] = $file;
$file = readdir($handle);
}
if ($files[0] === ".") { unset($files[0]); } // Unix specific?
if ($files[1] === "..") { unset($files[1]); }
foreach($files as $index => $file) // only keep files with image extensions
{ $pieces = explode(".", $file);
$extension = strtolower(end($pieces));
if ($extension !== "jpg") { unset($files[$index]); }
}
$files = array_values($files); // reset array
natcasesort($files); // and sort it.
return $files;
}
?>
<?php $imageDirectory = $_GET['directory'] . '/';
$imageNames = getImageNames($imageDirectory);
?>
imageNames = <?php echo json_encode($imageNames); ?>;
imageHeight = 400;
imageIndex = 0;
reloadImage(); // loads the first image based on height and index
}
所以我有这个混合PHP映射/数组元素的键和值。我想要的只是值,放在JavaScript中的字符串数组中
我有时会让它起作用,但其他人不会,我不知道有什么区别 我会这样做:
imageNames = <?php echo json_encode(array_values($imageNames)); ?>;
imageNames=;
我会这样做:
imageNames = <?php echo json_encode(array_values($imageNames)); ?>;
imageNames=;
我认为在对$imageNames
进行编码之前,在其上应用array\u值
函数应该可以做到这一点
imageNames=
我认为在对$imageNames
进行编码之前,在其上应用array\u值
函数应该可以做到这一点
imageNames=
json_encode()
需要一个以0开头的数组,否则它会将其转换为一个关联数组(即“map”)。@AlejandroIván你是说第一个元素位于索引0处的数组吗?是的,每个项都必须位于连续的索引中(0、1、2、3,…)。例如,如果存在以下索引:0、1、2、4。。。(缺少3),它将被编码为键值。非常好的提示,感谢json_encode()
需要一个以0开头的数组,否则它会将其转换为一个关联数组(即“map”)。@AlejandroIván你是说第一个元素位于索引0处的数组吗?是的,每个项都必须位于连续的索引中(0、1、2、3……)。例如,如果存在以下索引:0、1、2、4。。。(缺少3),它将被编码为键值。非常好的提示,谢谢