我喜欢在yii2中识别查找中的第一个元素,但我还没有想出办法来做到这一点,
这是代码:
$services = TblWorksTags::find()->where(["active"=>true])->all();
foreach ($services as $service){
echo '<li>'.$service->name.'</li>
}
从上面的代码我想让第一个项目具有不同的类,如
$services = TblWorksTags::find()->where(["active"=>true])->all();
foreach ($services as $service) {
//if its the first element
echo '<li class="active">'.$service->name.'</li> //this has a diffrent <li>
//for the other elements
echo '<li>'.$service->name.'</li>
}
答案 0 :(得分:1)
您可以通过以下某些counter
执行此操作: -
<?php
$services = TblWorksTags::find()->where(["active"=>true])->all();
$counter = 1;
foreach ($services as $service){
if($counter ==1){
//if its the first element
echo '<li class="active">'.$service->name.'</li>'; // quote and ; missed in your post
}else{
//for the other elements
echo '<li>'.$service->name.'</li>'; // quote and ; missed in your post
}
$counter++;
}
?>
我不知道Yii,所以如果以下代码: -
$services = TblWorksTags::find()->where(["active"=>true])->all();
为您提供索引数组(类似Array(0=>'something',1=>'something else', ......so on)
)。那么您可以像下面这样使用它的索引: -
<?php
$services = TblWorksTags::find()->where(["active"=>true])->all();
foreach ($services as $key=> $service){ //check $key is used here
if($key == 0){
//if its the first element
echo '<li class="active">'.$service->name.'</li>'; // quote and ; missed in your post
}else{
//for the other elements
echo '<li>'.$service->name.'</li>'; // quote and ; missed in your post
}
}
?>