【发布时间】:2020-03-03 00:26:42
【问题描述】:
我正在开发一个 php messenger 项目,该项目将 csv 文件中的最多 10 行作为数组读取到 php 中。 我想将“我”消息与“发件人”列中的“你”消息隔离开来。我想将每个字符串放在一个不同的变量中(减去“From”列),我最多有 5 个变量,“you”消息最多有 5 个变量。
我在想我需要对数组进行一个 foreach 循环,并且“如果”数组在 From 列中包含“me”,然后将字符串分配给变量 1,否则如果将字符串分配给变量 2 等...
如果在数组上,我正在努力想出 foreach 的方法。 以下代码当前输出的示例数据
From Time Message
me 03/02/2020 13:34 test message 001
you 03/02/2020 13:34 test message 002
me 03/02/2020 13:34 test message 003
you 03/02/2020 13:34 test message 004
me 03/02/2020 13:34 test message 005
you 03/02/2020 13:34 test message 006
me 03/02/2020 13:34 test message 007
you 03/02/2020 13:34 test message 008
me 03/02/2020 13:34 test message 009
you 03/02/2020 13:34 test message 010
<?php
$filename = 'messenger.csv';
// Open the file for reading
$datadump = [];
if (($h = fopen("{$filename}", "r")) !== FALSE)
{
// Each line in the file is converted into an individual array that we call $$
// The items of the array are comma separated
while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
{
// Each individual array is being pushed into the nested array
$datadump[] = $data;
}
// Close the file
fclose($h);
}
// Display the code in a readable format
$build = '<table><thead><th>From</th><th>Time</th><th>Message</th></thead><tbody>;
foreach($datadump as $row)
{
$build .= '<tr>';
foreach($row as $item)
{
$build .= "<td>{$item}</td>";
}
$build .= '</tr>';
}
$build .= '</tbody></table>';
echo $build;
?>```
【问题讨论】: