douniuta4783
2016-12-09 17:12
浏览 346
已采纳

在循环查询结果时循环遍历数组

I have a PHP/MySQL request returning data (ie: called "my_request"). I fetch through the results, and there comes my trouble... For each result, I need to check if the value is also in a hard-coded array (ie: called my_array"). I get the expected result, but it's echoed twice.

I should have: - my_request - while/loop through the results - echo 1 if the data is in my_array - echo 0 if the data is not in my_array

so : 00110000

I get : 0010000000010000

After serching here and there, I tried : - store the result / end the query loop / then loop through the array : no result

Here's a piece of the code :

$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"; }
}
}

this is where I get the double result! and can't find where I do wrong... Do I have to go back to store the result of the request, then use it for the array loop ? But how ? Or anything else ? Any clue ? thanks

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douweng5420 2016-12-09 20:00
    已采纳

    I had found this While and for loop not working I managed to work around the answer (by Vadim) to make my own now-working stuff ^^, so if it can be of any help to someone...

    /* 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 */
    }
    }
    
    打赏 评论

相关推荐 更多相似问题