我只是问自己,经过几年的开发,是否有一种更优雅的方法将 MySQL 结果格式化为关联数组,如下所示。
这里有一些虚拟代码,展示了我通常是如何做的。
$sql = 'SELECT field1, field2 FROM sample_table';
$res = $db->prepare($sql)->getAll();
$formatted = array();
foreach ($res as $row) {
$formatted[$row['field1']] = $row['field2'];
}
因为我经常做这些事情,所以我问自己是否有更优雅或更快捷的方法。
谢谢!
最佳答案
您可以创建一个类来处理重复性任务。这个想法是封装 您以后可以使用最少的代码重用的行为。这是一个基本示例。 请记住,您可能希望将数据库内容(连接、查询等)委托(delegate)给其他人。 到另一个类(class)。另请记住,此类特定于具有键值的数组 对(用于具有 2 列的查询)。
<?php
//Takes a two columns SQL query and format it to optain an array with key-value pair
class queryToMap{
private $formattedArray = array(); //The formated array
//Execute the query and format the array
public function executeQuery($sql){
$res = $this->dbQuery($sql);
while($row = $res->fetch_array()){
$this->formattedArray[$row[0]] = $row[1];
}
}
//Returns the formated array
public function getArray(){
return $this->formattedArray;
}
//Execute query and return the result
private function dbQuery($sql){
//DB connection...
$db = new mysqli("localhost", "bob", "123", "db");
//if the query is based on user input, better use prepared statement
$res = $db->query($sql);
return $res;
}
}
//Use of the class
$a = new queryToMap();
$a->executeQuery("SELECT F_CUST_ID, F_CUST_NAME FROM TP_CUSTOMER");
//Output the array
var_dump($a->getArray());
关于php - 有没有更优雅的方法在 PHP 中格式化 MySQL 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18083029/