[英]Grabbing Contents from File in PHP and then Converting Then into Arrays in JavaScript
我将“测试”中每个文件夹中的所有数据存储在一个未排序的数组中,因为以后使用这种方式对我来说会更简单。 设置完所有字符串数组后,我会将其回显到JavaScript,在JavaScript中将其处理为数组内部的数组。 有人可以告诉我我做错了吗? 我收到数百个错误。 最主要的是PHP中“测试”的路径不正确,因为它查找的是/Test/data.txt和/Test/properties.txt,而不是/ Test /(“测试”内部的文件夹)/data.txt和/测试/(“测试”中的文件夹)/properties.txt。 谢谢大家。
<?php
//Gets the path to the directory "Test" on the desktop
$userHome = realpath("./../../../../")."\\Desktop\\Test";
//Gets the name of all of the files inside of "Test"
$testFolderArray = array_diff(scandir($userHome), array("..", "."));
//Creates the arrays that will be exported
$dataArray = array();
$propertiesArray = array();
//For each value inside of test it runs this loop
foreach($x = 0; $x < count($testFolderArray); $x++) {
//Creates the path to the "data.txt" and "properties.txt" inside of each folder inside of the directory "test"
$dataFile = $userHome.$testFolderArray[$x]."\\data.txt";
$propertiesFile = $userHome.$testFolderArray[$x]."\\properties.txt";
//Reads the data inside of those files
$data = file_get_contents($dataFile);
$properties = file_get_contents($propertiesFile);
$dataArray[$x] = $data;
$propertiesArray[$x] = $properties;
}
/*
* By this point $dataArray and $propertiesArray should contain all of the information of all the files inside of the folders inside of "Test"
*
*/
?>
<!-- JavaScript -->
<script type="text/javascript">
//Should be exact copies of $dataArray and $propertiesArray
var data = '<?php echo json_encode($dataArray);?>';
var properties = '<?php echo json_encode($dataArray);?>';
//Where the sorted array wil be stored
var dataSorted = new Array();
var propertiesSorted = new Array();
//Run for each index of data inside of "data"
for(var x = 0; x < data.length; x++){
//Put tempArray inside the array dataSorted
var tempArray = data.split(",");
dataSorted[x] = tempArray;
}
//Run for each index of data inside of "properties"
for(var x = 0; x < properties.length; x++){
//Puts tempArray inside the array propertiesArry
var tempArray = properties.split(",");
propertiesSorted[x] = tempArray;
}
//By this point dataSorted and propertiesSorted should consist of arrays.
</script>
我承认我没有阅读所有代码,但是我猜这是两个错误:
var data = '<?php echo json_encode($dataArray);?>';
var properties = '<?php echo json_encode($dataArray);?>';
您将PHP数组编码为JSON,然后将其输入为Javascript-String。 您应该这样删除引号:
\n var data = <?php echo json_encode($ dataArray);?>;\n var properties = <?php echo json_encode($ propertiesArray);?>;\n
这将失败,因为json数据无法用于初始化Javascript数组。 假定逻辑中没有其他错误,则应使用JSON.parse('')解析Jsonified字符串。
另外,如果存在其他错误,则发布错误或至少告诉您js或php错误可能会有所帮助。
通常,JSON不是Javascript对象的子集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.