1

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?

4

2 回答 2

1

您可以为此使用数组内爆:http: //php.net/manual/en/function.implode.php

于 2013-09-28T00:35:47.807 回答
1

我试图运行一个虚拟测试。这是我的代码

<?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; ?>" />

我得到以下输出

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

或者你可以使用一个额外array的来存储这些stringsecho最后一个index

所以你的代码将更改为这个

<?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); ?>" />

我已经在我的虚拟值上测试过这两种方法,它对我来说效果很好。 先尝试使用第二种方法

于 2013-09-28T00:17:20.813 回答