0

在使用 MySQLi 和 ArrayObjects 时,这对我来说不是一个问题,而是一个学习路径。如果这对您来说是旧帽子,请随时为以下内容添加任何其他改进。如果是 MySQLi 和 ArrayObject 的新手,这是整个过程的一个简短示例。这比程序风格更有效。

查询:

//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"

谢谢

4

1 回答 1

-1

那么你“喜欢”改进什么?

我可以将整个 PHP 搜索方法等换成一个 SQL 查询

SELECT corg_name, corg_city FROM sometable WHERE corg_id = '$corg_id';

如果您可以通过选择 SQL 数据库中的 ID 轻松地返回一个结果,那么在 PHP 中搜索整个数组会容易得多。

于 2012-09-08T14:02:33.380 回答