Saturday, 28 September 2013

Turning SQL Distinct data into readable list in php

Turning SQL Distinct data into readable list in php

I have some custom tables in Wordpress that store information about
people, linked to a post, and I want to be able to generate a summary of
the data, specifically, a sentence along the lines of:
"This post mentions 4 surnames: Brown, Jones, Robinson and Smith"
I currently pull out the data as follows:
$surnames = $wpdb->get_results("
SELECT distinct lastname
FROM ".$wpdb->prefix."people
WHERE post_id='$post_id'
ORDER BY lastname asc");
Which returns an array of objects as follows:
Array (
[0] => stdClass Object ([lastname] => Brown )
[1] => stdClass Object ( [lastname] => Jones )
[2] => stdClass Object ( [lastname] => Robinson )
[3] => stdClass Object ( [lastname] => Smith )
)
So at the moment, I just do this:
foreach ($surnames as $surname) {$summary .= $surname->lastname.', ';}
which returns:
Brown, Jones, Robinson, Smith,
Clearly not acceptable.
Is there any standard php function that can do this, AND that will work on
an array of objects? I'd imagine this is a common problem, and I'm trying
to avoid reinventing the wheel if possible.

No comments:

Post a Comment