【问题标题】:How to increment $var value without a loop in PHP?如何在没有循环的情况下在 PHP 中增加 $var 值?
【发布时间】:2010-11-18 14:31:30
【问题描述】:

我有这个问题,我想用 1 增加一个值并将其应用到我的 HTML,但我不能使用 for()while() 循环(至少我认为我不能)。我正在定制一个电子商品程序(opencart),我的 php 知识不足以解决这个问题。

有这个功能可以显示商店的类别。它使用一个通过$var .= "value" 不断更新的变量。

到目前为止,我知道有多少子类别,但我不知道如何将此范围应用于我的 HTML。

我正在努力解决如下情况

<ul id="cats">
 <li id="cat1">Cat
  <ul id="sub1">
   <li>item</li>
   <li>item</li>
  </ul>
 </li>
 <li id="cat2">Cat
  <ul id="sub2">
   <li>item</li>
   <li>item</li>
  </ul>
 </li>
</ul>

我不知道如何增加 second 无序列表的计数。在生成第二个无序列表的代码下方。


[..]
$cPiD = strlen($parent_id);

if ($results) {
 if ($parent_id == 0) {
  $output .= '<ul id="cats">';
 } else {
  $output .= '<ul id="sub'.$cPiD.'">';
 }
}

[..]

变量$cPiD 保存子类别的总数(在本例中为2)。我希望此变量自动将正确的数字应用于无序列表(因此将id="sub1" 应用于第一个无序列表,将id="sub2" 应用于第二个无序列表(如上面的示例)。

问题是我不能在else 部分之后使用for() 循环,因为在我的HTML 中我会得到两个 &lt;ul&gt; 标签而不是一个。

在所有发生的 PHP 代码下方


$category_id = array_shift($this->path);
$output = '';
$results = $this->model_catalog_category->getCategories($parent_id);
$count = 0;
$cPiD = strlen($parent_id);

if ($results) { if ($parent_id == 0) { $output .= '<ul id="cats">'; } else { $output .= '<ul id="sub'.$cPiD.'">'; } }

foreach ($results as $result) { $count++; if (!$current_path) { $new_path = $result['category_id']; $output .= '<li id="cat'.$count.'">'; } else { $new_path = $current_path . '_' . $result['category_id']; $output .= '<li>'; }

$children = '';

$children = $this->getCategories($result['category_id'], $new_path);

$output .= $result['name'];

$output .= $children;

if (!$current_path) { $output .= '</li>'; } else { $output .= '</li>'; }

}

if ($results) { if ($parent_id == 0) { $output .= '</ul>'; } else { $output .= '</ul>'; } }

有人知道如何解决这个问题吗?

编辑: 哦,我尝试在foreach() 循环中添加以下结构,但是当某些类别没有任何子类别时会出现问题。

如果 (!$current_path) { $output .= '$result['name'] 。 '
    '; }别的{ $output .= $result['name']; }

【问题讨论】:

  • 你能检查一下这个问题的准确性吗?这对我来说没有意义。您声明“变量 $pCiD 包含子类别的总数”,但该变量在任何地方都不存在。变量 '$cPiD' 是一个字符串的长度,仅此而已......所以你能澄清一下吗?
  • 这只是(对我自己而言)知道存在多少子类别,我添加了变量可能会清除一些东西,但我想这不是那么重要..
  • $current_path 设置为什么?

标签: php opencart


【解决方案1】:

你可以用这个:

// at the top of your code (ouside of the loop)
$cPiD = 1;
// inside the loop you need to increment the parameter 
$output .= '<ul id="sub'.$cPiD++.'">';

每次使用该物品后,其值将增加1。(已使用后)

【讨论】:

  • 如果我使用它,我会得到两次 2,而不是先是 1,然后是 2(两个列表都将 cat2 作为 id 值)
  • 有意义,但是当有一个没有子类别的类别时,我会得到类似
    • 的输出(缺少 (或不必要的))
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签