2016-11-18 41 views
1

我沃爾德想確定在第一個元素找到所有在yii2,但我還沒有喜歡,就一定能做到這一點,yii2的findall和訪問的第一個元素

這是代碼:

$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

你的第二個代碼語法不正確。 ''''和';'錯過了。這是TYPO嗎? –

+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 
    } 
} 
?> 
+0

第二個使用關鍵作品 –

+0

@GEOFFREYMWANGI很高興幫助你歡呼:) :),順便說一句,第一個也會工作 –