[英]Last item in iteration with PHP
I want to separate iteration results by comma, but it's not an array. 我想用逗号分隔迭代结果,但它不是数组。 I want to do it in views, so code shouldn't be long.
我想在视图中执行它,因此代码不应该很长。
<?php foreach ($roles as $role): ?>
<?php echo $role->title; ?>
<?php endforeach; ?>
Result object implements Countable, Iterator, SeekableIterator, ArrayAccess. Result对象实现Countable,Iterator,SeekableIterator,ArrayAccess。
Not certain I understand what your asking (your code basically seems to do what you say?) the only thing i see missing is separate by comma. 不确定我理解你的要求(你的代码基本上看起来像你说的那样?)我唯一看到缺失的是用逗号分隔。
<?php
$first=true;
foreach ($roles as $role) {
if (!$first) echo ",";
$first=false;
echo $role->title;
}
?>
Or if caching is ok (string length isn't too long): 或者,如果缓存正常(字符串长度不是太长):
<?php
$output="";
foreach ($roles as $role) {
$output.=$role->title.",";
}
echo substr($output,0,-1);//Trim last comma
?>
If your $roles
variable is an object, write a method that returns an array of property values. 如果
$roles
变量是一个对象,请编写一个返回属性值数组的方法。 Something like: 就像是:
class Roles implements Countable, Iterator, SeekableIterator, ArrayAccess {
//main body of the class here
public function prop_as_array($prop){
if(!property_exists('Role', $prop)) throw new Exception("Invalid property");
$arr=array();
if(count($this)==0) return $arr
foreach($this as $role){
$arr[]=$role->$prop;
}
return $arr;
}
}
//on output page
$roles=new Roles;
echo implode(',', $roles->prop_as_array('title'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.