繁体   English   中英

php foreach:将每个循环结果放在一个变量中

[英]php foreach: put each of the loop result in one variable

我想这可能很简单,但我可以解决这个问题! 如何将每个循环结果仅放在一个变量中? 例如,

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $key => $value){
    $string = $value.',';
}

echo $string; 
// result 34,
// but I want to get - 28,16,35,46,34, - as the result

非常感谢,刘

你需要使用串联......

$string .= $value.',';

(请注意. )...

考虑对此特定方案使用内

$string = implode(',', $employeeAges);

你也可以试试

$string = '';
foreach( $employeeAges as $value){
    $string .= $value.',';
}

我试过了,它的确有效。

foreach( $employeeAges as $key => $value){
    $string .= $value.',';
}

您每次循环时都要重置字符串变量。 对于每个循环迭代,执行上述操作将$ value连接到$ string。

嗯,这个怎么样?

$string = "";
foreach( $employeeAges as $key => $value){
    $string .= $value.',';
}

您每次都要重置变量,这将以空字符串开头并每次都附加一些内容。 但是,有可能更好地完成这些任务的方式,例如在这种情况下内

尝试

$string = '';
foreach( $employeeAges as $key => $value){
    $string .= $value.',';
}

使用$ string = $ value。','; 你每次都要覆盖$ string,所以你只得到最后一个值。

尝试这个回声必须在里面然后{}变得好了

    $employeeAges;
    $employeeAges["Lisa"] = "28";
    $employeeAges["Jack"] = "16";
    $employeeAges["Ryan"] = "35";
    $employeeAges["Rachel"] = "46";
    $employeeAges["Grace"] = "34";

    foreach( $employeeAges as $key => $value){
        $string = $value.',';
        echo $string; 

    }

    // result - 28,16,35,46,34, - as the result

或其他方式

foreach( $employeeAges as $key => $value){
            $string .= $value.',';

        }
            echo $string; 
$string .= $value.',';

使用连接 ,在等号前加一个点。

您可以使用此详细语法:

$string = $string . $value . ',';

输入:

    $array = [1,2,3,4]

将所有数据保存在一个字符串中

    $string = "";
    foreach( $array as $key => $value){
        $string .= $value.',';
    }

输出:

    $string = '1,2,3,4,'

删除最后一个逗号

    $string =  rtrim($string, ',');

输出:

    $string = '1,2,3,4'

更多信息:

连接 ;

rtrim

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM