簡體   English   中英

遍歷數組,同時遍歷查詢結果

[英]Loop through an array while looping through a query result

我有一個PHP / MySQL請求返回數據(即:稱為“ my_request”)。 我獲取了結果,但麻煩來了...對於每個結果,我都需要檢查該值是否也位於硬編碼數組中(即:稱為my_array“)。我得到了預期的結果,但回顯了該結果。兩次。

我應該具有:-my_request-while / loop through the results-如果數據在my_array中,則回顯1-如果數據不在 my_array中,則回顯0

:00110000

我得到:0010000000010000

在這里和那里閑逛之后,我嘗試了:-存儲結果/結束查詢循環/然后遍歷數組:無結果

這是一段代碼:

$my_array = array('Monday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00'), 'Tuesday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00') /* and so on 'til saturday */ );

$query = " SELECT date, start FROM table WHERE id=2 AND date='2016-12-08' ORDER BY start ";
$resultats = $conn->query($query) or die ("Error :" . mysql_error());

while ($hours = mysqli_fetch_assoc($resultats))
{
extract($hours);

echo" ( $date / $start ) "; /* results are ok , let's say I have 2 resultst ie: 9:00 and 10:00 */

foreach ($my_array as $hour) {
    if( $hour == $start ) { echo"done"; } else { "fail"; }
}
}

這就是我得到雙重結果的地方! 並且找不到我在哪里做錯了...我是否必須返回存儲請求的結果,然后將其用於數組循環? 但是如何? 還是其他? 有什么線索嗎? 謝謝

我發現雖然While和for循環不起作用,但我設法解決了這個問題(由Vadim撰寫),使我自己的現在可以工作的東西^^,所以,如果這對某人有幫助的話...

/* query used below has been prepared at the beginning of the script */
$not_available_hours = array();
$myday = $specialHours[$theday];

$results = $stmt1->execute();
$stmt1->bind_result($date, $start);
$stmt1->store_result();

if ($stmt1->num_rows > 0) {

while($stmt1->fetch()){

$start = strtotime($start);
$debut = date("G:i", $start);

$not_available_hours[] = $debut;
}

foreach ($myday as $hour) {
    if (in_array($hour, $not_available_hours)) {
    $finish = strtotime($hour) + 3600; 
    $fin = date("G:i", $finish);
    echo"already booked !"; /* grey line */
    } else {
$finish = strtotime($hour) + 3600; 
$fin = date("G:i", $finish);
echo"get it !"; /* available -> green line */
}
}

暫無
暫無

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

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