Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to automatically convert database query results into arrays in laravel

Shulou Source: shulou.com Published: 2022-06-02 06:37:17 10月09日 Update

Laravel how to automatically convert the database query results into an array, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.

In the project, I came across again that the result queried from the database in laravel is an object, and it is not easy to use toArray. Once I changed it before, I remember it was / confing/database.php, 'fetch' = > PDO::FETCH_OBJ, and this line changed to' fetch' = > FETCH_ASSOC'. But what I am doing now is a secondary development, so if this is changed, what I have done before may go wrong, and then look for it and check it, and the result is like this

Quote

Use PDO; DB::setFetchMode (PDO::FETCH_ASSOC); $rs = DB::table ('vrtourl')-> get ()

It can be solved.

PDO::FETCH_ASSOC / / gets an associative array indexed by column names from the result set. PDO::FETCH_NUM / / gets an array of values indexed by the numeric offset of the column in the row from the result set. PDO::FETCH_BOTH / / this is the default value and contains the above two arrays. PDO::FETCH_OBJ / / gets an object whose attributes correspond to each column name from the record of the current row of the result set. PDO::FETCH_BOUND / / returns TRUE using fetch () and assigns the acquired column value to the corresponding variable specified in the bindParm () method. PDO::FETCH_LAZY / / creates an associative array and an indexed array, as well as an object that contains column properties, so that you can choose one of the three interfaces.

Another way:

Function objectToArray ($object) {/ / encodes into a json string and then decodes it into an array of return json_decode (json_encode ($object), true);} is it helpful for you to read the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Tags: Array result object index data database query property method association help line clear bad thing middle finger content again impression variable Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL NVidia MariaDB macOS Docker