簡體   English   中英

PHP比較While循環外的While循環的值

[英]PHP Comparing Values From While Loop Outside Of Loop

我正在嘗試找到比較while statement之外的日期的最佳方法。 我編寫了一個函數,並在其中設置了while循環。 考慮到我需要將循環中的每個日期與$this_new_date進行比較,如何實現呢?

 function getDates(){
 $returnDates = array();
 while($result = mysqli_fetch_array($allDatesQuery)){
 $returnDates[] = date("Y-n-j",strtotime($result['date']));
}}


if($returnDates===$this_new_date){

//do something here
}

您可以執行以下操作:

...    
$matchedDates = array_filter($returnDates, function($value) use($this_new_date){
    return $value == $this_new_date;
});
var_dump($matchedDates);

請注意,如果要使用MySQLi擴展名( http://php.net/manual/en/book.mysqli.php ),則除非您運行PHP> =,否則將需要使用while循環來存儲數據。 5.3在這種情況下,您可以使用mysqli_fetch_allhttp://php.net/mysqli_fetch_all )。

選項1

在查詢中執行日期比較。 這將是您絕對最佳/最快的選擇。 這樣,PHP甚至不需要執行任何操作。

例:

SELECT * FROM table WHERE date = ?;

然后使用准備好的語句將您的日期值傳遞給查詢: http : //php.net/manual/en/mysqli.quickstart.prepared-statements.php

選項2

假設您需要在PHP中執行此日期比較, while循環仍將是最快的,因為除非您要查找的日期是最后一條記錄,否則您可能無需閱讀整個查詢結果就可以逃脫。

function is_date_in_query($this_new_date, $allDatesQuery) {
    while($result = mysqli_fetch_array($allDatesQuery)) {
        if (strtotime($this_new_date) == strtotime($result['date'])) {
            return TRUE;
        }
    }
    return FALSE;
}

if (is_date_in_query($this_new_date, $allDatesQuery)) {
    // yes the date is inside - do something
}
else {
    // no the date is not inside - do something else
}

但是您說您不能使用while循環,所以讓我們看看另一個選項。

選項3

結合使用mysqli_fetch_allin_arrayarray_column 這樣可以防止任何while循環,但需要您加載整個查詢結果。

例:

// Put ALL rows into an array
$result_array = mysqli_fetch_all($allDatesQuery, MYSQLI_ASSOC);

// Check if the date is anywhere in the result array
if (in_array(date('Y-m-d', strtotime($this_new_date)), array_column($result_array, 'date'))) {
    // yes the date is inside - do something
}
else {
    // no the date is not inside - do something else
}

這是一個工作示例(已更新): https : //eval.in/868105

暫無
暫無

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

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