如何将PDO返回的关联数组内容转换为普通数组

3
我正在使用PHP PDO,并让它返回一个关联数组。
我可以循环遍历PDO创建的关联数组,但是我不知道如何从函数中返回该数组。
function wantedrentals($provence, $country, $dbh)
   {
      echo "Now in wanted wanted rentals function<br><br>"; 

      $journeyrentalssarray = array();

      $sth = $dbh->query("SELECT summary, url, provence, country from tblAccomadation WHERE country = $country ");

    # setting the fetch mode
    $sth->setFetchMode(PDO::FETCH_ASSOC);

    while($row = $sth->fetch()) 
        {
            echo $row['summary'] . "\n";
            echo $row['url'] . "\n";
            echo $row['provence'] . "\n";
            echo $row['country'] . "\n";
        }

  return $journeyrentalssarray;
  }

我很新手 PHP 和 PDO,希望得到任何帮助。

你对 var_dump( $row ); 得到了什么? - Prafulla Kumar Sahu
你可能想看一下这个:PDOStatement::fetchAll。这个函数将整个结果作为一个数组返回。 - Yury Fedorov
2个回答

1
function wantedrentals($provence, $country, $dbh)
   {
      echo "Now in wanted wanted rentals function<br><br>"; 

      $journeyrentalssarray = array();

      $sth = $dbh->query("SELECT summary, url, provence, country from     tblAccomadation WHERE country = '$country' ");

    # setting the fetch mode
    $sth->setFetchMode(PDO::FETCH_ASSOC);

    while($row = $sth->fetch()) 
        {
            $journeyrentalssarray[] = $row; // add $row to $journeyrentalssarray array
            echo $row['summary'] . "\n";
            echo $row['url'] . "\n";
            echo $row['provence'] . "\n";
            echo $row['country'] . "\n";
        }

  return $journeyrentalssarray;
  }

感谢您的反馈。如果发布的解决方案对您有效,您应该将其标记为“解决方案”以奖励答案的积分。 - maxhb

-1

你可能想要这样

function wantedrentals($provence, $country, $dbh)
   {
      echo "Now in wanted wanted rentals function<br><br>"; 

      $journeyrentalssarray = array();

      $sth = $dbh->query("SELECT summary, url, provence, country from tblAccomadation WHERE country = $country ");

    # setting the fetch mode
    //$sth->setFetchMode(PDO::FETCH_ASSOC);

    return $sth->fetch(PDO::FETCH_ASSOC);
  }

PDO::FETCH_ASSOC 会返回一个由列名索引的数组,该数组与结果集中返回的列名相对应。

在成功调用 fetch 函数时,返回值取决于获取类型,在本例中为 FETCH_ASSOC;如果失败,则返回 FALSE。

有关更多信息,请阅读此处

我们还可以使用 fetchAll 来获取所有结果集行的数组。因此,函数可能如下所示。

function wantedrentals($provence, $country, $dbh)
       {
          echo "Now in wanted wanted rentals function<br><br>"; 

          $journeyrentalssarray = array();

          $sth = $dbh->query("SELECT summary, url, provence, country from tblAccomadation WHERE country = $country ");


        return $sth-> fetchAll(PDO::FETCH_ASSOC);
      }

如需更多信息,请阅读此处


这将仅返回1行,然后停止。 - Rizier123
这对你有帮助吗?:D - jameshwart lopez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接