我正在循环浏览一个可能包含以下信息的电子表格:
To From
LAX/SAF/ORL ORL/SAF
LAX/DUB DUB/SAF
SAF/LON LON/BNE/SYD
我需要循环显示这些信息,以便得到类似的信息:
Result 1: Lax -> Orl
Result 2: Lax -> Saf
Result 3: Saf -> Orl
Result 4: Saf -> Saf
Result 5: Orl -> Orl
Result 6: Orl -> Saf
这是我到目前为止所做的:
$row = "LAX/SAF/ORL";
$row2 = "ORL/SFO";
preg_match_all('([A-Za-z]+)', $row, $matches);
foreach ($matches[0] as $location_to){
echo $location_to . " -> " . $row2 . "<br />"; //currently doesn't loop through row2
}
我怎么能这样做但是对于这两组数据呢?我现在已经陷入困境了......如上所述两次以获得我需要的输出。
非常感谢任何帮助(这需要通过一个循环运行,因为它是电子表格中的一行并且还有其他分配的数据)。
这基本上是一种多次入境的事情。
由于
答案 0 :(得分:3)
根据您所拥有的内容,尝试:
$row = "LAX/SAF/ORL";
$row2 = "ORL/SFO";
$arow = explode("/", $row);
$arow2 = explode("/", $row2);
foreach($arow as $p1) {
foreach($arow2 as $p2) {
echo "$p1 -> $p2 <br>";
}
}
这将创建您正在寻找的输出类型,因为您已经知道$row
和$row2
是什么^^
答案 1 :(得分:1)
/
那么之后就是这样:
$file = fopen('/path/to/file.csv', 'r');
// skip headers
fseek($file, 1);
while($row = fgetcsv($file)) {
$from = explode('/', $row[0]);
$to = explode('/', $row[1]);
foreach($from as $i => $sender) {
$recipient = isset($to[$i]) ? $to[$i] : 'undefined';
echo "$sender -> $recipient";
}
}
答案 2 :(得分:1)
你实际上相当接近。我会这样做:
$row = "LAX/SAF/ORL";
$row2 = "ORL/SFO";
$from = explode('/', $row);
$to = explode('/', $row2);
foreach ($from as $f){
foreach($to as $t) {
echo $f . " -> " . $t . "<br />";
}
}
编辑:您可能需要为if ($f == $t)
添加支票,因为ORL - &gt; ORL并没有多大意义。 :)
答案 3 :(得分:0)
您可以使用嵌套的foreach并遍历$ row2匹配,如下所示:
$row = "LAX/SAF/ORL";
$row2 = "ORL/SFO";
$to_locations = explode('/', $row);
$from_locations = explode('/', $row2);
foreach ($to_locations as $to){
foreach ($from_locations as $from) {
echo $to . " -> " . $from . "<br />";
}
}
答案 4 :(得分:0)
试试这个:
$row = "LAX/SAF/ORL";
$row2 = "ORL/SFO";
$rows = array($row, $row2);
foreach ($rows as $row) {
preg_match_all('([A-Za-z]+)', $row, $matches);
foreach ($matches[0] as $location_to){
echo $location_to . " -> " . $row2 . "<br />"; //currently doesn't loop through row2
}
}
基本上,您将为$rows
数组中的每个元素执行代码。
将来,如果你有更多的行(即文件的每一行),你只需将它们添加到$rows
数组,代码就会遍历每一行。
答案 5 :(得分:0)
$row = "LAX/SAF/ORL";
$row2 = "ORL/SFO";
$first_array = explode('/', $row);
$second_array = explode('/', $row2);
$result_array = array();
$assoc_array = array();
foreach($first_array as $value1) {
foreach($second_array as $value2) {
$assoc_array[$value1] = $value2;
$result_array[] = $value1.' -> '.$value2;
}
}
如果您愿意,这将导致您拥有一个关联的数组,或者一个将具有LAX形式的字符串的数组 - > ORL