【问题标题】:Loop through an array while looping through a query result在遍历查询结果的同时遍历数组
【发布时间】:2016-12-09 17:12:19
【问题描述】:

我有一个 PHP/MySQL 请求返​​回数据(即:称为“my_request”)。 我查看了结果,然后我的麻烦来了…… 对于每个结果,我需要检查该值是否也在硬编码数组中(即:称为 my_array")。 我得到了预期的结果,但它被回显了两次。

我应该有: - 我的请求 - while/循环遍历结果 - 如果数据在 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"; }
}
}

这是我得到双重结果的地方!并且找不到我做错的地方...... 我是否必须返回存储请求的结果,然后将其用于数组循环?但是如何?还是别的什么? 有什么线索吗?谢谢

【问题讨论】:

  • 请注意$my_array 是二维的。
  • 这如何改变输出? (我的意思是,我从请求中读取数组和数据都没有问题,这就是为什么我无法弄清楚我做错了什么以获得多个结果而我只需要得到一个......)

标签: php mysql


【解决方案1】:

我找到了这个While and for loop not working 我设法解决了答案(由 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 */
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 2021-10-22
    • 1970-01-01
    • 2015-05-09
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多