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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c