-
数据库(书表)
序列号 价格
0001 10.00 0001 30.00 0002 15.00 0004(A) 9.00 0004(B) 5.00 0005 3.00(注:0003无记录) -
代码
$serialID = array("0001","0002","0003","0004","0005"); //DB Connection for($i = 0; $i < count($serialID); $i++) { $q = "select * from book where serial like '"$serialID[$i]%'" limit 1"; $r = mysqli_query($dbc,$q); while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $serial[$i] = $row['serial']; $price[$i] = $row['price']; echo $serial[$i].' '.$price[$i]; } } //pass db value into array for($j = 0; $j < count($serialID); $j++) { $data[$j] = array($serialID[$j],$price[$j]); }
-
这次我的问题是如何跳过 serialID 0003 值?
-
我的预期输出:(回声$serial[$i]。'.$price[$i])
0001 10.000002 15.000003
0004(A) 9.000005 3.00
将最后一个循环修改为
for($j = 0; $j < count($serialID); $j++)
{
if(null != $price[$j]){
$data[$j] = array($serialID[$j],$price[$j]);
}
}
但我的问题是,循环查询某些内容不是很诱人吗?也许你应该使用"IN"语句?还是"或"?例如:
foreach($serialId as $id){
$string.= ' %'.$serialId. ' % OR '; //of course you should check if this is first or last cell in array. So you don’t add unnecessary OR or space
}
select * from book where serial like '"$string'" limit 1
只需在 for 循环中检查它。使用以下代码
$serialID = array("0001","0002","0003","0004","0005");
//DB Connection
for($i = 0; $i < count($serialID); $i++)
{
$q = "select * from book where serial like '"$serialID[$i]%'" limit 1";
$r = mysqli_query($dbc,$q);
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$serial[$i] = $row['serial'];
if($serialID=="0003"){
$price[$i] = $row['price'];
}
echo $serial[$i].' '.$price[$i];
}
}
//pass db value into array
for($j = 0; $j < count($serialID); $j++)
{
$data[$j] = array($serialID[$j],$price[$j]);
}
希望这对你有帮助
我认为这段代码应该更适合您的需求:
$serialID = array("0001", "0002", "0003", "0004", "0005");
//DB Connection
foreach ($serialID as $serialItem) {
$q = "select * from book where serial like '"$serialItem%'" limit 1";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
if (count($row) > 0) {
echo $row['serial'] . ' ' . $row['price'];
//pass db value into array
$data[] = array(
'serial' => $row['serial'],
'price' => $row['price']
);
}
}
}
// debug output
print_r($data);
$serialID = array("0001","0002","0003", "0004","0005");
$preparing = [];
foreach($serialID as $value) {
$preparing[] = "'" . $value . "'";
}
$sql = "select * from book where serial IN (" . implode(',', $preparing) . ")";
$query = mysqli_query($sql);
$data = mysqli_fetch_all($query, MYSQLI_ASSOC);