Php 要在查找集合中查找的数组值
存储在数据库中的数据如下所示,其中下午、晚上是列名,逗号分隔的字符串是它们的值Php 要在查找集合中查找的数组值,php,Php,存储在数据库中的数据如下所示,其中下午、晚上是列名,逗号分隔的字符串是它们的值 morning = 'Fri,Sun'; afternoon = 'Thrs,Fri,Sat,Sun'; evening = 'Thrs,Fri,Sat,Sun'; 此查询可用于: AND ( FIND_IN_SET( 'Sat', posts.afternoon ) OR FIND_IN_SET( 'Sat', posts.evening ) ) 但我想要这样的东西,但我知道不能: AN
morning = 'Fri,Sun';
afternoon = 'Thrs,Fri,Sat,Sun';
evening = 'Thrs,Fri,Sat,Sun';
此查询可用于:
AND ( FIND_IN_SET( 'Sat', posts.afternoon )
OR FIND_IN_SET( 'Sat', posts.evening ) )
但我想要这样的东西,但我知道不能:
AND ( FIND_IN_SET( 'Fri','Sat', posts.afternoon )
OR FIND_IN_SET( 'Thrs','Fri','Sat', posts.evening ) )
所以我想至少像下面这样单独搜索,我已经测试过并得到了结果:
AND ( FIND_IN_SET ('Fri', posts.afternoon) OR FIND_IN_SET ('Sat', posts.afternoon) OR FIND_IN_SET ('Sat', posts.evening))
问题是如何修改我现有的PHP脚本来匹配这个,请?以下是我的完整代码:
<?php
JSON formatted data received via ajax
$return = '{"avail":["Wed-2,Thrs-2","Thrs-3"]}';
In the above -1 means for monrning, -2 for afternoon and -3 for evening.I'm categorising them below.'
$avail = $data['avail'];
$days = array();
$cols = array();
$size = sizeof($avail);
if(($avail != "")&&($size > 1)){
$periods = array();
foreach($avail as $v){
list($day, $column) = explode("-", $v); // make sure you validated the data to avoid errors
$periods[$column][] = "'" . mysql_escape_string($day) . "'"; //strtolower// PHP would automatically create an empty array if $periods[$column] was not defined
}
$intToCol = array(1 => "morning", 2 => "afternoon", 3 => "evening");
// $periods should now be identical to ["2" => ["'sun'", "'mon'"], "3" => ["'sun'"]]
$conditions = array();
foreach($periods as $int => $days){
$dayString = implode(",", $days);
$conditions[] = " FIND_IN_SET ($dayString, posts." . $intToCol[$int].")" ;
}
$add_here = "AND (" . implode(" OR ", $conditions) . ")";
}else if(($avail != "")&&($size == 1))
{
foreach($avail as $k=>$v)
{
$v;
$array = explode('-', $v);
$day =$array[0]; // Wed
$column = $array[1]; // 2
if($column == 1)
{
$col = "morning";
}
if($column == 2)
{
$col = "afternoon";
}
if($column == 3)
{
$col = "evening";
}
}
$add_here = " posts.".$col." = '".$day."' ";
$sql = "SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(('$lat' - lat) * pi()/180 / 2), 2) +COS('$lat' * pi()/180) * COS(lat * pi()/180) * POWER(SIN(('$lon' - lon) * pi()/180 / 2), 2) ))) as distance from posts WHERE posts.subname LIKE '%$subject%' AND posts.pricing <= '$rate' ".$add_here."".$IsTutionCentre." GROUP BY posts.UUID having distance <= '$distance' order by distance";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$place=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$place[] = $row;
}
$_SESSION['subject'] = $place;
//send back to ajax call made page
echo json_encode($place);
}
?>
此MySQL函数find_in_set()只能在一组字符串中搜索一个字符串
第一个参数是字符串,因此无法将逗号分隔的字符串解析为字符串(在集合元素中根本不能使用逗号!)。第二个参数是一个集合,它又由一个逗号分隔的字符串表示,因此您希望在集合(“p,q,r”,“p,q,r,s”)中找到集合(“p,q,r,s”),这很好,但根据定义,它肯定无法在任何集合中找到字符串“p,q,r”-它包含逗号
您可以使用如下命令:
where setcolumn like '%p,q%'