如何以最短的方式循环:
$db->setQuery("SELECT val1 FROM table1 WHERE val2 = 'AAA'");
$row1 = $db->loadObjectList();
$var1 = $row1[0];
$db->setQuery("SELECT val3 FROM table1 WHERE val2 = 'AAA'");
$row2 = $db->loadObjectList();
$var2 = $row2[0];
$db->setQuery("SELECT val1 FROM table1 WHERE val2 = 'BBB'");
$row3 = $db->loadObjectList();
$var3 = $row3[0];
$db->setQuery("SELECT val3 FROM table1 WHERE val2 = 'BBB'");
$row4 = $db->loadObjectList();
$var4 = $row4[0];
...
$db->setQuery("SELECT val1 FROM table1 WHERE val2 = 'AAA'");
$row997 = $db->loadObjectList();
$var997 = $row997[0];
$db->setQuery("SELECT val3 FROM table1 WHERE val2 = 'AAA'");
$row998 = $db->loadObjectList();
$var998 = $row998[0];
$db->setQuery("SELECT val1 FROM table1 WHERE val2 = 'BBB'");
$row999 = $db->loadObjectList();
$var999 = $row999[0];
$db->setQuery("SELECT val3 FROM table1 WHERE val2 = 'BBB'");
$row1000 = $db->loadObjectList();
$var1000 = $row1000[0];
我有1000个这样的查询,我不得不绕过它们。
另外,我是否需要逐个声明所有全局变量,即$ var1,$ var2,... var1000,还是可以循环?
答案 0 :(得分:1)
创建查询数组并像这样迭代
$var = array(); // storing result in this array
$array_qry = array("SELECT val1 FROM table1 WHERE val2 = 'AAA'","SELECT val3 FROM table1 WHERE val2 = 'AAA'");// array of query
foreach($array_qry as $qry) {
$db->setQuery($qry);
$row = $db->loadObjectList();
$var[] = $row[0];
}
然后迭代$var
以获取存储值
答案 1 :(得分:0)
$resultArray = array(); $queryParam = array('AAA', 'BBB', 'CCC'); // Add Query param value $fieldArray = array('val1', 'val3','val4') // Add field attributes foreach($queryParam as $qryPrm) { foreach($fieldArray as $field) { $sql= "select ". $field . " from mytable where val2 = '".$qryPrm."'"; $db->setQuery($qry); $row = $db->loadObjectList(); $resultArray[] = $row[0]; } }
这对你有用吗?