Remove first comma from on-the-fly string
As I'm a bit of php noob, I'm not sure whether to go with preg_replace()
or to explode()
then implod开发者_开发百科e()
. Either way, I don't know how to go about it.
I'm in wordpress, and I'm running this code:
<?php $terms = wp_get_post_terms($post->ID,'jobtype');
foreach($terms as $term){echo ', ' . $term->name;} ?>
I need to capture into a string the echo ', ' . $term->name;
and remove that first ', '
.
Even if there's a different way I can echo
the term names, could you guys (and gals) help me out?
Thanks!
Old school:
$terms = wp_get_post_terms($post->ID,'jobtype');
$names = array();
foreach($terms as $term){
$names[] = $term->name;
}
echo implode(',', $names);
As PHP 5.3 introduced anonymous functions [docs], array_map
[docs] becomes more interesting for these "one time" jobs:
echo implode(',', array_map(function($term) { return $term->name; },
wp_get_post_terms($post->ID,'jobtype')));
Or maybe more descriptive with a reusable function:
function getProperty($prop) {
return function($object) use ($prop) {
return $object->{$prop};
}
}
echo implode(',', array_map(getProperty('name'),
wp_get_post_terms($post->ID,'jobtype')));
But as said, this only works if you use PHP 5.3.
精彩评论