为foreach循环生成唯一ID?

时间:2013-08-17 02:35:39

标签: php foreach

当前我使用切换来显示/隐藏详细信息。我需要在foreach循环中为每个div提供一个唯一的ID。我不知道如何使它适用于回声字符串。你能救我吗?

<?php
$i = 0; 
    foreach ( $payment as $payment_id => $items ) {
        foreach ( $items as $item ) {
            $i++;
            $count = 0;
            // Echo, need to show unique ID in both $count, it must be the same
            echo '<p><strong><a href="#">Link</a></strong>
            <br/><a href="#" class="show_info" id="'.$count.'">Show Details</a>
            <div id="payment_info_'.$count.'" style="display:none;">';
            ++count;
        }
    }
?>

我需要在代码上的2个位置进行$ count是相同的。我的代码出错了。

谢谢

更新: 实际上代码不仅仅是我在这里给出的。我尝试使用你的代码但是没有用。

您可以在http://www.codesend.com/view/7d58acb2b1c51149440984ec6568183d/(pasw:123123)

查看完整版

3 个答案:

答案 0 :(得分:1)

  1. 您已撰写++count而非++$count
  2. 您似乎没有使用$i
  3. 您正在每个循环初始化$count
  4. 这应该有效:

    <?php
    $i = 0; /* Seems redundant */
    $count = 0;
        foreach ( $payment as $payment_id => $items ) {
            foreach ( $items as $item ) {
                $i++; /* Seems redundant */
                // Echo, need to show unique ID in both $count, it must be the same
                echo '<p><strong><a href="#">Link</a></strong>
                <br/><a href="#" class="show_info" 
                        id="dtls'.$count.'">Show Details</a>
                <div id="payment_info_'.$count.'" style="display:none;">';
                ++$count;
            }
        }
    ?>
    

答案 1 :(得分:0)

<强>第一

将其删除或将其放在foreach循环之外:

$count = 0;

<强>第二

不要仅使用 id 的数字,并将其与字符或单词一起使用,如下所示:

id = "element'.$count.'"

第三:

什么是$i

如果没用就删除它!

<强>第四

++count更改为++$count

代码:

<?php
$i = 0; 
$count = 0;
    foreach ( $payment as $payment_id => $items ) {
        foreach ( $items as $item ) {
            $i++;
            // Echo, need to show unique ID in both $count, it must be the same
            echo '<p><strong><a href="#">Link</a></strong>
            <br/><a href="#" class="show_info" id="info_'.$count.'">Show Details</a>
            <div id="payment_info_'.$count.'" style="display:none;">';
            ++$count;
        }
    }
?>

答案 2 :(得分:0)

++ count 错误,应该是++ $ count;

试试这个

<?php
$i = 0; 
    foreach ( $payment as $payment_id => $items ) {
        foreach ( $items as $item ) {
            $i++;
            $count = 0;
            // Echo, need to show unique ID in both $count, it must be the same
            echo '<p><strong><a href="#">Link</a></strong>
            <br/><a href="#" class="show_info" id="'.$count.'">Show Details</a>
            <div id="payment_info_'.$count.'" style="display:none;">';
            ++$count;
        }
    }
?>
相关问题