简体   繁体   English

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

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

I just asked myself, after a few years of development, if there is a more elegant way of formatting MySQL results into associative arrays like the one below. 经过几年的发展,我只是问自己,是否有一种更优雅的方式将MySQL结果格式化为如下所示的关联数组。

Here some dummy code that shows how I usually do it. 这里有一些伪代码,显示了我通常的做法。

$sql = 'SELECT field1, field2 FROM sample_table';
$res = $db->prepare($sql)->getAll();
$formatted = array();

foreach ($res as $row) {
    $formatted[$row['field1']] = $row['field2'];
}

As I'm doing things like these super often, I asked myself if there is a more elegant or quicker way. 当我经常做这样的事情时,我问自己是否有一种更优雅或更快捷的方法。

Thanks! 谢谢!

You can create a class to handle the recurring tasks. 您可以创建一个类来处理重复任务。 The idea is to encapsulate the behaviors that you can reuse later with the minimum amount of code. 这个想法是封装行为,您以后可以用最少的代码重用这些行为。 Here's a basic example. 这是一个基本示例。 Keep in mind that you may want to delegate the database stuff (connection, queries, etc.) to another class. 请记住,您可能希望将数据库内容(连接,查询等)委派给另一个类。 Also keep in mind that this class is specific to an array with key-value pairs (to be use with a query with 2 columns). 还要记住,该类特定于具有键-值对的数组(与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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM