你可能不想要第一个或最后的/
,也许它是这样的更好。
foreach($o as $k => $v){
$a[] = "$k-$v";
}
echo implode('/', $a);
function foo($obj){
foreach($o as $k => $v){ // this will fail if there are any more -public- variables declared in the class.
$a[] = "$k-$v";
}
return implode('/', $a);
}
echo foo($yourobject);
class foo{
$transaction = 'sale';
$type = 'apartment';
$city = 'washington';
$rooms = 1;
function __tostring(){ // or a normal method name.
foreach($self as $key => $value){ // this will fail if there are more variables declared in this class.
$a[] = "$key-$value";
}
return implode('/', $a);
}
function bar(){ // will always work.
return "transaction-{$self->transaction}/type-{$self->type}/city-{$self->city}/rooms-$self->rooms";
}
}
echo $myobj;
echo $myobj->bar();
或者这样(或任何以上的它的变化):
$s = "" // must be done to avoid PHP strict errors, code will function anyways.
foreach($o as $k => $v){
$s .= "$k-$v/";
}
echo substr($s, 0, -1);
总体而言,我更喜欢第一种方法,但由于你有一个物体它ight实际上可以用它做些事情。
'$ data =“”; foreach($ obj as $ key => $ o): $ data。= $ key .'-'。$ o。'/'; endforeach; $ data = trim('/',$ data); echo $ data;' –
试试这个,让我知道 –
没有核心功能。你拥有的就足够了。 –