dougan7523 2012-04-12 06:28
浏览 30
已采纳

PHP强制重置计数器为0

I have a counter of menu items, that basically add incremental value as a class to a menu system:

    <?php
    if ($element['#original_link']['depth'] == 1) {
      static $counter = 0;
      $counter++;
      $class = 'count-' .  $counter;
    }
    $output = 'some output code build';
    return '<li class="' . $class . '">' .$output .'</li>';
    ?>

Note, the code is inside each menu item (outside a loop or array). The code will simply output the lists of unordered list, without UL:

<li class="count-1">One</li>
<li class="count-2">Two</li>, ...etc.

This works fine until I change the source of menus.

1). One is using the system menu of my CMS,

2). the latter is using a block output of that system menu,

and both output similar construct of menus, except for the fact that the latter continues the counter from the #1 rather than a reset from a 1 (although #1 is not activated once #2 takes over the place). I haven't figured out why, but it seems that #2 is a continuance of #1. While I expect each should start an increment from 1.

I can not use a reset here. Is there anything obvious I missed that PHP can handle here, apart from the the way of my CMS do to the counters?

Any pointer would be very much appreciated. Thanks

UPDATE, actual codes in use:

function mytheme_menu_link(array $variables) {
  //dpm($variables);
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == variable_get('menu_main_links_source', 'main-menu')) {
    if ($element['#original_link']['depth'] == 1) {     
       static $counter = 0;
       $counter++;                    
       $element['#attributes']['class'][] = 'count-' .  $counter;
    }
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>
";
}

/**
 * Implements theme_menu_tree()
    No helpful variables, except for a flattened render of tree
 */
function mytheme_menu_tree__main_menu($variables) {
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}
  • 写回答

1条回答 默认 最新

  • drymoeuka282427675 2012-04-12 06:48
    关注

    When using static variables, the values of the variable will not be reset between subsequent executions of the same code. That's the express purpose of static. Get rid of it if you do not want that behavior.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳