你好 我想從PHP傳遞幾個數組到javascript。對於其中的一些而言,它適用,對其他則不適用。我得到一組文件名和一個包含幾個文本文件內容的數組。從PHP傳遞數組到javascript
<?php
$album="./images/text_".$benutzerLang."_album1/";
$fileArray=lsRandom("./images/album1");
$listTextArray=initTexts($album,$fileArray);
$falseArray=lsRandom("./images/album2");
print $listTextArray[0];
?>
<script language="javascript" type="text/javascript">
var filesArray=new Array(5);
var falseArray=new Array(5);
var textListArray=new Array(5);
<?php
$i=0;
foreach($fileArray as $element){
print 'filesArray['.$i.']="'.$element.'";';
$i++;
}
$i=0;
foreach($falseArray as $element){
print 'falseArray['.$i.']="'.$element.'";';
$i++;
}
$i=0;
foreach($listTextArray as $element){
print 'textListArray['.$i.']="'.$element.'";';
$i++;
}
?>
function createText(){//...
</script>
<?php
function lsRandom($foldername){
$files = array();
$returnFiles=array();
$indexes=array();
$currentPath=getcwd();
chdir($foldername);
// Get the all files and folders in the given directory.
$files = glob("*", GLOB_BRACE + GLOB_MARK);
$indexes=(array_rand($files,5));
shuffle($indexes);
foreach($indexes as $in){
$returnFiles[$in]=$files[$in];
}
chdir($currentPath);
return $returnFiles;
}
function getFileText($fileName,$path){
$filePath=''.$path.''.$fileName.'';
//$file=fopen($filePath,'r');
//$text=fread($file,filesize($filePath));
$text=file_get_contents($filePath,false);
return $text;
}
function initTexts($album, $images){
$textArray1=array();
$i=0;
foreach($images as $im){
$nameArray=explode(".",$im);
$textName=''.$nameArray[0].'.txt';
$textArray1[$i]=getFileText($textName, $album);
$i++;
}
return $textArray1;
}
?>
問題是$ listTextArray。在第8行中,我可以打印整個數組$ listTextArray,其中包含一些小文本文件的內容,它可以工作。但在'foreach - loop'中進一步下降。它不再工作了。只要我在第二個php塊中使用變量$ listTextArray,我的其他代碼就不會再執行了。我不知道爲什麼它不能訪問該部分的$ listTextArray。因爲它對其他數組$ fileArray和$ falseArray沒有問題。
沒有不匹配 - 在PHP中使用JS和'$ listTextArray'中的'textListArray'。不過,使它們在不同語言中相同可能有助於減少混淆。 :-) – 2011-05-10 23:12:18
感謝您的回答 – kapukinz 2011-05-11 12:46:41