有没有一种更优雅的方法可以在PHP中格式化MySQL结果


Is there a more elegant way to format MySQL results in PHP?

经过几年的开发,我刚刚问自己,是否有一种更优雅的方法可以将MySQL结果格式化为关联数组,如下所示。

这里有一些伪代码,展示了我通常是如何做到的

$sql = 'SELECT field1, field2 FROM sample_table';
$res = $db->prepare($sql)->getAll();
$formatted = array();
foreach ($res as $row) {
    $formatted[$row['field1']] = $row['field2'];
}

当我经常做这样的事情时,我问自己是否有更优雅或更快的方法。

谢谢!

您可以创建一个类来处理重复任务。其想法是将以后可以用最少的代码重复使用的行为。这是一个基本的例子。请记住,您可能想要委派数据库的内容(连接、查询等)去另一个班。还要记住,此类特定于具有键值的数组对(用于具有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());