2014-04-20 4 views
-4

루프의 모든 항목에 특정 숫자를 부여하는이 함수가 있습니다.카운터를 사용하는 php 함수 간략화

<?php $counter =0; ?> 
<?php while(have_rows('profs_associes')): the_row(); ?> 
    <?php 
    ++$counter; 
    if($counter == 1) {$imageclass = 'data-contentid="1"';} 
    if($counter == 2) {$imageclass = 'data-contentid="2"';} 
    if($counter == 3) {$imageclass = 'data-contentid="3"';} 
    if($counter == 4) {$imageclass = 'data-contentid="4"';} 
    if($counter == 5) {$imageclass = 'data-contentid="5"';} 
    if($counter == 6) {$imageclass = 'data-contentid="6"';} 
    if($counter == 7) {$imageclass = 'data-contentid="7"';} 
    if($counter == 8) {$imageclass = 'data-contentid="8"';} 
    if($counter == 9) {$imageclass = 'data-contentid="9"';} 
    if($counter == 10) {$imageclass = 'data-contentid="10"';} 
?> 
<div class="img-row" <?php echo $imageclass; ?>> 

그러나 그것이 간단하게 할 수있는 것 같다 단순히 말했다 항목의 a를 '아이디'와 같은 항목의 수를 설정 하나 개의 함수를 작성하여 (내가 많이해야 할). 아무도 도와 줄 수 있습니까?

+0

있는지 확인 이렇게하면 아이디어를 얻을 수 있습니다. http://stackoverflow.com/questions/4676417/should-i-use-curly-brackets-or-concatenate-variables-within-string s – mustaccio

+0

달성하려는 목표와 그 문제점을보다 구체적으로 설명하십시오. 좋은 질문을하는 방법에 대한 조언과 Jon Skeet의 블로그 글 [완벽한 질문 작성하기] (http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect- question.aspx). "황금률"에 특히주의를 기울이십시오. 그러나 전체 기사를 읽으라고 강력히 권합니다. –

답변

0

그냥 관련 제자리에 카운터의 값을 할당 :

<?php while(have_rows('profs_associes')): the_row(); ?> 
    <?php 
    ++$counter; 
    $imageclass = 'data-contentid="'.$counter.'"'; 
0
++$counter; 
$imageclass = 'data-contentid="'.$counter.'"'; 

나는 이것이 당신이하려는 일이라고 생각합니다. . 연산자 concatenates 문자열에 대한 $counter의 값입니다.

0

당신은 열고 닫는 PHP 태그를 많이 가지고, 당신은 그나마 필요 (실제로는 전혀) 그렇게.)

<?php 
$counter =0; 
while(have_rows('profs_associes')): the_row(); 
    echo '<div class="img-row" data-contentid="'.(++$counter).'">': 
} 
?> 

을 그리고 당신은 루프에 10 배를 원한다면, 우리는 (에 대한이 있습니다 :

<?php 
$counter =0; 
while(have_rows('profs_associes')): the_row();// Not really sure what's going on here 
    ++$counter; 
    $imageclass = 'data-contentid="'.$counter.'"'; 
    echo '<div class="img-row" '.$imageclass.'>': 
} 
?> 

당신은 더욱 최소화 할 수

<?php 
for($counter=1; $count<=10; $counter++){ 
    echo '<div class="img-row" data-contentid="'.$counter.'">': 
} 
?>