douyan2002 2013-09-27 23:39
浏览 18
已采纳

对foreach的反应奇怪

i am trying to concatenate values into a string which later is attached to a hidden input.

This is the forach loop:

<?php
    $langid     = array();
    $transLang      = '';
    foreach($translator['langs'] as $lang) {

        $curlang    = $lang->term_id;
        $langid[]   = $curlang;
        $transLang  .= '('.$curlang.'), ';

        // for testing
        echo $transLang."<br />";
    }
?>
<input type="hidden" name="selectedLang" value="<?php echo $transLang; ?>" />

.

The langid[] array grabs everything correctly
but $transLang echoed into the input only shows the first value which is: (3),

When i use this line:

echo $transLang."<br />";

Which i added for testing it echoes:

(3),
(3), (10),
(3), (10), (12),
(3), (10), (12), (27),
(3), (10), (12), (27), (19),
(3), (10), (12), (27), (19), (20),

The last one is the complete string after the foreach finished runing but the input field value is always only the first run meaning (3),

Any idea why this is happening?

  • 写回答

2条回答 默认 最新

  • doulangbizhan5160 2013-09-28 00:17
    关注

    I tried to run a dummy test. Here is my code

    <?php
    
        $a = "";
        $loop = array("1","2","3","4","5","6","7","8","9");
        foreach($loop as $i){
            $a .= "($i),";
        }
    
    
    ?>
    <input type="hidden" name="selectedLang" value="<?php echo $a; ?>" />
    

    and i get the following output

    <input type="hidden" name="selectedLang" value="(1),(2),(3),(4),(5),(6),(7),(8),(9),">
    

    OR You ca use an additional array to store these strings and echo the last index

    So Your code will changed to this one

    <?php
        $langid     = array();
        $strings    = array();
        $transLang      = '';
        foreach($translator['langs'] as $lang) {
    
            $curlang    = $lang->term_id;
            $langid[]   = $curlang;
            $transLang  .= '('.$curlang.'), ';
            $strings[] = $transLang;
            // for testing
            //echo $transLang."<br />";
        }
    ?>
    <input type="hidden" name="selectedLang" value="<?php echo end($strings); ?>" />
    

    Both methods I've tested on my dummy values and it's working fine for me. Try to use second method first.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)