我试图根据时间从php返回一些数据。例如,如果当前时间大于发布时间,那么只有发布数据应该发送给用户,否则他应该被告知这是它的计划。问题是,即使满足条件,它仍然执行循环并给我"成功"的结果。有办法克服吗?
$sql = "Select posts.post_title,posts.author_name,posts.publish_date,posts.post_content,comments.name,comments.comment,comments.time_posted "
. "from posts left join comments "
. "on posts.id=comments.post_id "
. "where posts.id=$data->id "
. "LIMIT 5";
$result = mysql_query($sql) or trigger_error(mysql_error() . $sql);
$count = mysql_num_rows($result);
$index = 0;
if ($count >= 1) {
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if (strtotime($data->now) > strtotime($row['publish_date'])) {
if ($index == 0) {
$results[$index]['post_title'] = $row['post_title'];
$results[$index]['author_name'] = $row['author_name'];
$results[$index]['publish_date'] = $row['publish_date'];
$results[$index]['post_content'] = $row['post_content'];
$temp[$index]['name'] = $row['name'];
$temp[$index]['comment'] = $row['comment'];
$temp[$index]['time_posted'] = $row['time_posted'];
} else {
$temp[$index]['name'] = $row['name'];
$temp[$index]['comment'] = $row['comment'];
$temp[$index]['time_posted'] = $row['time_posted'];
}
$index++;
} else {
$response['status'] = 'Scheduled';
$response['message'] = 'Data present';
break;
}
}
$results[0]['comments'] = $temp;
$response['status'] = 'Success';
$response['message'] = 'Data present';
$response['results'] = $results;
} else {
$response['status'] = '404';
$response['message'] = 'Post does not exist';
}
echo json_encode($response);
所以我设法通过使用一个标志变量
来解决它$flag = true;
if ($count >= 1) {
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if ((strtotime($data->now) > strtotime($row['publish_date'])) == true) {
if ($index == 0) {
$results[$index]['post_title'] = $row['post_title'];
$results[$index]['author_name'] = $row['author_name'];
$results[$index]['publish_date'] = $row['publish_date'];
$results[$index]['post_content'] = $row['post_content'];
$temp[$index]['name'] = $row['name'];
$temp[$index]['comment'] = $row['comment'];
$temp[$index]['time_posted'] = $row['time_posted'];
} else {
$temp[$index]['name'] = $row['name'];
$temp[$index]['comment'] = $row['comment'];
$temp[$index]['time_posted'] = $row['time_posted'];
}
$index++;
} else {
$flag = false;
}
}
if ($flag == false) {
$response['status'] = 'Scheduled';
$response['message'] = 'Data present';
} else {
$results[0]['comments'] = $temp;
$response['status'] = 'Success';
$response['message'] = 'Data present';
$response['results'] = $results;
}
不管你的条件是否满足,你总是初始化状态为success($response['status'] = ' success ';)。您需要将这一行移动到满足条件时执行的代码块中。