Generating Comma-Separated Strings from Object Array Columns
When working with databases and arrays of objects, it becomes necessary to generate comma-separated strings from specific columns. One common issue is having an extraneous comma after the last value.
To address this, a preferred method is to create a new array. For each object in the original array, extract the desired value and store it in the new array. This approach ensures that the last element will not have a trailing comma.
Here's an improved code snippet:
$resultstr = array(); foreach ($results as $result) { $resultstr[] = $result->name; } echo implode(",", $resultstr);
The above is the detailed content of How to Avoid Trailing Commas When Creating Comma-Separated Strings from Object Arrays?. For more information, please follow other related articles on the PHP Chinese website!