2016-11-07 64 views
-1

我使用以下代碼來顯示特定聯盟的總年數,但每年顯示1。如何顯示foreach循環中的元素總數?

例如,西班牙甲級聯賽已經三年,但它顯示的1,1,1代替3

我已經使用count($object);sizeof($object);但沒有得到想要的結果。

See the image

這裏是我的代碼:

<div class=" reds clearfix"; style="width: 50%;"> 
    <ul id="test"> 
     <!-- the loop --> 
     <?php while ($fixture_query->have_posts()) : $fixture_query->the_post(); ?> 
      <?php 
      $champion_team = get_post_meta(get_the_ID(), 'football_league_team_name', true); 
      $terms_competition = get_the_terms(get_the_ID(), 'competition'); 
      $terms_session = get_the_terms(get_the_ID(), 'session'); ?> 

      <?php foreach ($terms_session as $object) {?> 
       <li style="float: left; margin-right: 5px;"> <?php echo $object->name; ?></li> 
       <?php 
       //echo count($object); // output 2 
       echo sizeof($object); 
       // echo count($object->name); 
       ?> 
      <?php } ?> 

     <?php endwhile; ?> 
     <!-- end of the loop --> 
     <?php wp_reset_postdata(); ?> 
    </ul> 
</div> 
+0

爲什麼標記爲js? –

+0

它也可以用js來解決。不是嗎? –

+0

您可能需要echo sizeof($ terms_session); ... –

回答

0

我假設你要顯示的foreach循環內的會話總數。

基於您的代碼,就可以計算出會話總數爲

$total_sessions = count($terms_session);

現在你可以很容易地使用這個變量foreach循環內的

<?php 
    foreach ($terms_session as $object) {?> 
     <li style="float: left; margin-right: 5px;"> <?php echo $object->name; ?></li> 
     <?php 
     echo $total_sessions; 
     ?> 
<?php } 
?> 

下面是完整的代碼如有更改,請參閱添加註釋。

<div class=" reds clearfix"; style="width: 50%;"> 
    <ul id="test"> 

    <!-- the loop --> 
    <?php while ($fixture_query->have_posts()) : $fixture_query->the_post(); ?> 
     <?php 
     $champion_team = get_post_meta(get_the_ID(), 'football_league_team_name', true); 
     $terms_competition = get_the_terms(get_the_ID(), 'competition'); 
     $terms_session = get_the_terms(get_the_ID(), 'session'); 
     // Calculate the total number of sessions 
     $total_sessions = count($terms_session); 
     ?> 
     <?php 
     foreach ($terms_session as $object) {?> 
     <li style="float: left; margin-right: 5px;"> <?php echo $object->name; ?></li> 
     <?php 
     // Display the total number of sessions 
     echo $total_sessions; 
     ?> 
     <?php } 
     ?> 

    <?php endwhile; ?> 
    <!-- end of the loop --> 

    <?php wp_reset_postdata(); ?> 
    </ul> 


</div> 
0
<?php 
echo count($terms_session);//this give all count of elements 
foreach ($terms_session as $object) { ?> 
    <li style="float: left; margin-right: 5px;"> <?php echo $object->name; ?></li> 
    <?php 
    //echo count($object); // output 2 
    echo sizeof($object); 
    // echo count($object->name); 
    ?> 
<?php } 
?> 
+2

請爲此代碼的做法以及它如何直接回答問題添加一些說明。 –

相關問題