在foreach中多个赋值数组?

时间:2015-09-01 08:48:47

标签: php arrays

我是php的新手......我想要显示4个数组,但它没有显示任何内容....

请参阅代码

$new_strip_from_name[] = $strip_from_name;
$new_from_name[] = $from_name;
$new_to_name[] = $to_name;  
$new_lastdata[] = $lastdata;

echo "<table style='border: 2px solid black; text-align:left'>";    
    foreach($new_from_name as $from_name2){
        foreach($new_lastdata as $lastdata2){
            foreach($new_to_name as $to_name2){
                foreach($new_strip_from_name as $key => $value){                
                    if((strpos($lastdata2, $value) !==FALSE)){                  
                     echo "<tr>";
                     echo "<td>$from_name2</td>";
                     echo "<td>$to_name2</td>";
                     echo "<td>$lastdata2</td>";
                     echo "</tr>";  
                    }

                }
            }
        }
    }
echo "</table>";

示例数组

$new_strip_from_name = array("okay");
$from_name; = array("john", "mar", "jeff");
$to_name; = array("phil", "india", "japan");
$lastdata; = array("john@okay", "mar@okay", "jeff@not");

期望的输出

john    phil    john@okay
mar     india   mar@okay

2 个答案:

答案 0 :(得分:0)

好的,现在我们看到你想要的!!但它不会像这样工作。最好的方法是为此创建一个类 - &gt; http://php.net/manual/en/language.oop5.basic.php。但这里有一个可行的基本解决方案:

$messages = array();
$message = array();
$message['from'] = "john";
$message['to'] = "phil";
$message['lastdata'] = "john@okay";

array_push($messages, $message);

为每条消息或其他任何消息执行此操作,然后执行以下操作:

foreach ($messages as $message){
  if (strpos($message,"okay") !== false){
      echo "<tr>";
      echo "<td>".$message['from']."</td>";
      echo "<td>".$message['to']."</td>";
      echo "<td>".$message['lastdata']."</td>";
      echo "</tr>";  
   }
}

答案 1 :(得分:0)

这个anwser应该适用于您当前的数据结构,但这不是很干净。它不是应该的方式,每个消息应该有1个元素,而不是4个消息的4个数组,这可能会导致一些严重的混淆问题。如果可能,您应该更改数据的收集或​​创建。但无论如何试试这个:

$new_strip_from_name[] = $strip_from_name;
$new_from_name[] = $from_name;
$new_to_name[] = $to_name;  
$new_lastdata[] = $lastdata;

echo "<table style='border: 2px solid black; text-align:left'>"; 
for ($i = 0; $i < sizeof($new_from_name); $i++){
  if (strpos($new_lastdata[$i],"okay") !== false){
   echo "<tr>";
   echo "<td>".$new_from_name[$i]."</td>";
   echo "<td>".$new_to_name[$i]."</td>";
   echo "<td>".$new_lastdata[$i]."</td>";
   echo "</tr>"; 
  }
} 
echo "</table>";