我是一名学生,目前正在学习 PHP,但很难让explode() 函数按照我想要的方式工作。
以下文本文件“vacations.txt”包含:
"54321", "Big Island Hawaii", "2999.00", "Best beaches big volcano"
"87654", "Cruise Caribbean", "3500.00", "Ocean view with balcony Cancun Jamaica etc."
"09876", "Rome and Madrid", "3999.00", "I see Italy I see Spain"
"32198", "Ski Tahoe", "1200.00", "Ski all day Gamble all night"
我尝试将其放入由逗号分隔的数组中。使用 print_r(),我可以看到它全部进入数组的第一个索引。 这是我的代码:
function displaySpecials() {
$prodString = include("vacation.txt");
$vacArray = explode(',', $prodString );
print_r($vacArray);
}
这是输出:
"54321", "Big Island Hawaii", "2999.00", "Best beaches big volcano" "87654", "Cruise Caribbean", "3500.00", "Ocean view with balcony Cancun Jamaica etc." "09876", "Rome and Madrid", "3999.00", "I see Italy I see Spain" "32198", "Ski Tahoe", "1200.00", "Ski all day Gamble all night"Array ( [0] => 1 )
我已经搜索并阅读了我能找到的有关explode()的所有内容,但我无法弄清楚为什么会发生这种情况。我的最终目标是在一个 4 行 4 列的表中输出一个多维数组,以显示文本文件中的 16 个值。
非常感谢所有帮助。预先感谢您!
最佳答案
The include statement includes and evaluates the specified file.
include将评估其中的任何内容,基本上包括其他 php 脚本。
您需要获取其内容。
下面我使用了file逐行获取文件内容。
function displaySpecials() {
$lines = file("vacation.txt"); // will return lines in array
foreach($lines as $line){ // loop for each line
$vacArray[] = explode(",", $line); // insert resulting array to last index of $varArray
}
print_r($vacArray);
return $vacArray;
}
此外,该文件似乎是常规的 .csv
,您可以使用 fgetcsv
。查看官方的例子docs 。
关于phpexplode() 将文本文件中的所有值存储到索引 [0],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36526050/