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

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站