Using ThinkPHP6 Collection Methods to Process Database Query Results
The article explains how ThinkPHP6 returns query results as a Collection object, introduces its useful methods such as toArray and isEmpty, and provides a PHP code example demonstrating how to check for empty results and convert the collection to an array.
In ThinkPHP6, after executing a database query, the returned value is a think\Collection object, which can be manipulated similarly to an array but requires specific collection methods for processing.
The most commonly used methods are toArray , which converts the collection to a plain PHP array, and isEmpty , which checks whether the collection contains any records.
Below is a code example that queries the shop_goods table, checks if the result is empty, and prints both the original collection and its array representation:
$select = Db::table('shop_goods')->whrer('id', 1)->select(); if ($select->isEmpty()) { echo '数据为空'; exit; } print_r($select); print_r($select->toArray()); }
When the query returns data, the output shows the collection object structure followed by the corresponding array, illustrating how the toArray method simplifies further data handling.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.