使用 yii2 findall 并访问第一个元素
using yii2 findall and accessing the first element
我想在 yii2 中识别 find all 中的第一个元素,但我还没有找到一种方法来做到这一点,
这是代码:
$services = TblWorksTags::find()->where(["active"=>true])->all();
foreach ($services as $service){
echo '<li>'.$service->name.'</li>
}
根据上面的代码,我希望它的第一项具有不同的 class,例如
$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>
}
您可以通过一些 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
}
}
?>
我想在 yii2 中识别 find all 中的第一个元素,但我还没有找到一种方法来做到这一点,
这是代码:
$services = TblWorksTags::find()->where(["active"=>true])->all();
foreach ($services as $service){
echo '<li>'.$service->name.'</li>
}
根据上面的代码,我希望它的第一项具有不同的 class,例如
$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>
}
您可以通过一些 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
}
}
?>