使用MySQLi和ArrayObjects时,这不是一个问题,而是一个学习途径。如果这对您来说是旧帽子,请随意添加以下任何其他改进。如果是MySQLi和ArrayObject的新手,这是整个过程的一个简短示例。哪个FAR比程序风格更有效率。
查询:
//constants for mysqli credentials, DB_HOST,DB_UNAME etc.
include('dbase');
//zip code to seach
$zipcode = 10003;
//instantiate the object variable
$mysqli = new mysqli(DB_HOST,DB_UNAME,DB_UPWORD,DB_NAME);
//run the query searching for matching records using a regular expression
$result = $mysqli->query("SELECT corg_id, corg_name, corg_city FROM sometable WHERE corg_zip REGEXP '^$zipcode';");
//using fetch_object() returns an ArrayObject
while ($row = $result->fetch_object()){
$zipmatch[] = $row;
}
//assign to session var for later use, in another script
$_SESSION['queryresult'] = $zipmatch;
所以此时查询返回了一个结果。生成的ArrayObject如下所示:
Array
(
[0] => stdClass Object
(
[corg_id] => 1
[corg_name] => Acme Home Improvement
[corg_city] => New York
)
[1] => stdClass Object
(
[corg_id] => 2
[corg_name] => ABC Handy Work
[corg_city] => New York
)
[2] => stdClass Object
(
[corg_id] => 3
[corg_name] => Wile E Coyote Repairs
[corg_city] => New York
)
)
输出: 让我们说我们想从上面的数据切片中获得一条记录。由于这是一个数组对象,因此一些循环结构将返回错误,因为它们需要字符串而不是对象引用。 foreach将采用对象引用或数组。
function selected($arrObject,$searchString,$result){
foreach($arrObject as $v){
if ($v->corg_id==$searchString){
$result[] = $v->corg_name; //string, would be index 0
$result[] = $v->corg_city; //string, would be index 1
}
}
return $result;
} //close selected function
$result = array(); //array of returned search data
$haystack = $_SESSION['queryresult']; //arrayObject to search
$needle = 3; //look for a matching id in the arrayObject
//instantiate an output array with the result of the selected function
$outputArray=selected($haystack,$needle,$result);
$comName = $outputArray[0]; //string
$comCity = $outputArray[1]; //string
echo $comName; //outputs "Wile E Coyote Repairs"
echo $comCity; //outputs "New York"
由于
答案 0 :(得分:-1)
那么你“喜欢”改进是什么?
我可以将整个PHP搜索方法等交换为一个单独的SQL查询
SELECT corg_name, corg_city FROM sometable WHERE corg_id = '$corg_id';
如果您可以通过选择SQL数据库中的ID轻松返回一个结果,那么在PHP中搜索整个数组会更容易。