0

我正在遍历一个电子表格,其中可能包含如下信息:

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
}

除了两组数据,我怎么能做到这一点?我目前被困在如何......像上面一样 foreach 两次以获得我需要的输出。

任何帮助将不胜感激(这需要通过一个循环运行,因为它是电子表格上的一行并且具有其他分配的数据)。

它基本上是一个多行程条目之类的东西。

谢谢

4

6 回答 6

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是^^

于 2013-02-25T01:12:39.323 回答
1
  1. 如果可以的话,它的电子表格将其读取为 CSV
  2. 为什么是正则表达式?只是爆炸/

然后是这样的:

$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";
   }  
}
于 2013-02-25T01:06:44.890 回答
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 -> ORL 并没有真正的意义。:)

于 2013-02-25T01:12:34.547 回答
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 />";
  }
}
于 2013-02-25T01:12:20.257 回答
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数组中,代码就会遍历每一行。

于 2013-02-25T01:13:26.443 回答
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 形式的字符串的数组

于 2013-02-25T01:13:58.620 回答