请帮我优化以下foreach循环。它适用于小型数组,当循环很短但问题是,有时,当数组变大时,它会强制查询在foreach内循环很多次,这导致我的服务器阻塞抛出一个503错误。我需要以某种方式在foreach之外进行查询,但仍然能够选择WHERE cat = $ id [0] AND sub = $ id [1] AND fir = $ id [2]。
foreach($array as $id){
$query=mysqli_query($con,"SELECT * FROM table WHERE cat=$id[0] AND sub = $id[1] AND fir = $id[2]");
$thiss = mysqli_fetch_array($query);
echo $thiss['name'];
}
答案 0 :(得分:1)
$ands = array();
foreach ($array as $id) {
$ands[] = "(cat=$id[0] AND sub = $id[1] AND fir = $id[2])";
}
$ors = implode(' OR ', $ands);
$query = mysqli_query($con, "SELECT name FROM TABLE WHERE $ors";
while ($thiss = mysqli_fetch_assoc($query)) {
echo $thiss['name'];
}
答案 1 :(得分:1)
我不会详细说明为什么我建议你重新考虑你的查询逻辑,但对于手头的任务,试试这个:
$where=array();
foreach($array as $id){
$where[]="cat=$id[0] AND sub = $id[1] AND fir = $id[2]";
}
$sql='SELECT * FROM table WHERE ('.implode(') OR (',$where).')';
$query=mysqli_query($con,$sql);
while ($thiss = mysqli_fetch_array($query))
echo $thiss['name'];
答案 2 :(得分:0)
试试这个
$cat = $sub = $fir = '';
foreach($array as $id){
$cat .= $id[0].',';
$sub .= $id[1].',';
$fir .= $id[2].',';
}
$cat = substr_replace($cat, '', -1);
$sub = substr_replace($sub, '', -1);
$fir = substr_replace($fir, '', -1);
$sql = "SELECT * FROM table WHERE `cat` IN ($cat) AND `sub` IN($sub) AND `fir` IN ($fir)";
$query=mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($query)) {
echo $row['name'];
}