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

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

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 */
    }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?