foreach里面的foreach只显示一个结果

时间:2017-09-21 14:25:59

标签: php mysql foreach

<dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>org.mongodb.spark</groupId>
        <artifactId>mongo-spark-connector_2.11</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-mllib_2.10</artifactId>
        <version>2.2.0</version>
    </dependency>

实际上,下面的查询会返回8个结果。

$con=mysqli_connect("localhost","root","","database");
// Check connection 
   if (mysqli_connect_errno())
 {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }
 error_reporting(E_ALL ^ E_NOTICE);
 $query = "SELECT * FROM TT_posts WHERE post_status='publish' AND 
ping_status='open'";
 $result = $con->query($query);
 while($row1 = $result->fetch_assoc()) 
 foreach ($result as $row1){

$image = "SELECT * FROM TT_posts WHERE post_title='$row1[post_name]'";
 $result1 = $con->query($image);
 while($row2 = $result1->fetch_assoc()) 
 foreach ($result1 as $row2){
 echo "<img src='".$row2[guid]."'>";
 echo "<p>".$row1[post_title]."</p>";
 }}
 ?>

执行循环时,它会在第一个结果处停止。我不知道究竟是什么阻止了代码。

1 个答案:

答案 0 :(得分:0)

我认为您的变量名称已经混淆了。您的第一个while会向$row1分配一行,然后您的foreach引用$result,而不是$row1。变量$row1实际上在每次循环foreach时都会被覆盖。

您实际上并不需要foreach

while ($row1 = $result->fetch_assoc()) {
  $image = "SELECT * FROM TT_posts WHERE post_title='$row1[post_name]'";
  $result1 = $con->query($image);
  while ($row2 = $result1->fetch_assoc()) { 
    echo "<img src='".$row2[guid]."'>";
    echo "<p>".$row1[post_title]."</p>";
  }
}