簡體   English   中英

如何在php中的函數中返回多個對象,然后顯示它們

[英]How can I return multiple objects in a function in php and then display them

public function getdata()
{
    $ctrObj =  new Country();
    $result = $ctrObj->ctrydata($this->table);
    if(mysqli_num_rows($result)>0){
        while ($row = mysqli_fetch_array($result)) {
            return $row;
        }
    }
}
$ctryObj = new CountryController();
$countries = $ctryObj->getdata();
print_r($countries);

當我print_r($countries); 然后我只能看到一個對象,但如果我在上面提到的函數中打印出來,我找到了所有對象。

您可以將結果保存在數組中並返回它:

public function getdata()
{
    $data = []; // Init array
    $ctrObj =  new Country();
    $result = $ctrObj->ctrydata($this->table);
    if(mysqli_num_rows($result)>0){
        while ($row = mysqli_fetch_array($result)) {
            $data[] = $row; // Populate it
        }
    }
    return $data; // Return it
}

因為您只返回一個結果,所以可以像這樣更改

public function getdata()
    {
    $ctrObj =  new Country();
    $result = $ctrObj->ctrydata($this->table);
    $rows = [];
    if(mysqli_num_rows($result)>0){
        while ($row = mysqli_fetch_array($result)) {
             $rows[] = $row;
         }
     }
    return $rows;
   }

你可以屈服:

public function getdata()
{
    $ctrObj =  new Country();
    $result = $ctrObj->ctrydata($this->table);
    if(mysqli_num_rows($result)>0){
        while ($row = mysqli_fetch_array($result)) {
            yield $row;
        }
    }
}

你會像這樣使用它(對記憶有很多好處......):

$ctryObj = new CountryController();
foreach ($ctryObj->getdata() as $country) {
    print_r($country);
}

編輯:我已經學習了PDO並且從未接觸過mysqli所以我試圖找到一個與fetchAll()相當的東西,顯然,你也有一個fetch all函數( http://php.net/manual/ fr / mysqli-result.fetch-all.php )。

我認為你的代碼看起來像這樣:

public function getdata()
{
    $ctrObj =  new Country();
    $result = $ctrObj->ctrydata($this->table);
    if (mysqli_num_rows($result) > 0) {
        $rows = mysqli_fetch_all($result);

        return $rows;
    }
}

這看起來更有效,一個接一個地獲取所有對象,將它們綁定到一個數組中(因為它本身就是由php完成的)。 無論如何,如果你不想復制結果緩沖區,請使用yield (一個用於mysql端,另一個用於php端)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM