【发布时间】:2015-11-24 23:30:36
【问题描述】:
我有以下数组,我想将它们中的每一个都转换为单独的字符串。换句话说,将数组分解成单独的部分。
$formatsArray = $_POST['formats'];
$topicsArray = $_POST['topics'];
这是因为我想在以下查询中包含单个字符串“
$resources = "select * from resources where
stage LIKE '%".$stage."%'
AND format LIKE '%".$formats."%'";
$run_query = mysqli_query($con, $resources);
这是因为 format 需要一个单独的字符串进行比较,例如假设数组是 ["video", "blogs", "articles"],如果 format 要与 video,blogs,articles 进行比较,则它将不起作用,而是视频、博客或文章。
我希望这很清楚,如有任何澄清,请告知。
一切顺利,
更新:
$formats = explode(',', $formatsArray);
$topics = explode(',', $topicsArray);
$resources = "select * from resources where
stage LIKE '%".$stage."%'
AND format LIKE '%".$formats."%' AND topic LIKE '%".$topics."%' ";
更新:
$run_query = mysqli_query($con, $resources);
while($row = mysqli_fetch_array($run_query)) {
$data[] = array(
'format' => $row['format'],
'title' => $row['title'],
'costs' => $row['cost'],
'stage' => $row['stage'],
'topic' => $row['topic'],
'link' => $row['link']
);
}
更新
include('db.php');
$query = 'select * from resources where ';
$query .= 'stage LIKE :stage and';
$execute[':stage'] = '%' . $stage . '%';
if(!empty($_POST['formats'])){
foreach($_POST['formats'] as $key => $format) {
$query .= 'format LIKE :format' . $key . ' and ';
$execute[':format' . $key] = '%' . trim($format) . '%';
}
}
if(!empty($_POST['topics'])){
foreach($_POST['topics'] as $key => $topic) {
$query .= 'topic LIKE :topic' . $key . ' and ';
$execute[':topic' . $key] = '%' . trim($topic) . '%';
}
}
$query = rtrim($query, ' and ');
if(!empty($execute)) {
$stmt = $con->prepare($query);
$stmt->execute($execute);
} else {
echo 'You must search for something';
}
while($row = mysqli_fetch_array($query)) {
$data[] = array(
'format' => $row['format'],
'title' => $row['title'],
'costs' => $row['cost'],
'stage' => $row['stage'],
'topic' => $row['topic'],
'link' => $row['link']
);
}
【问题讨论】:
-
所以逗号是分隔符?使用 explode 然后遍历数组并构建您的查询。使用准备好的语句。
-
感谢您的回复。逗号不是分隔符。在数据库中,您有例如“video”或“blogs”或“articles”,因此如果数组使用逗号(例如 video,blogs,articles)内爆,则它不会匹配任何条目。您能否详细说明您的解决方案
-
不是内爆,而是爆炸。所以你有
$_POST['formats']这是video,blogs,articles对吗?因此,如果您在,上爆炸然后遍历该数组,您将分别拥有每个术语.. -
感谢我在最初的帖子底部添加了更新。我将如何进行下一步
-
$formats和$topics总是有相同数量的元素?