我认为这可能非常简单,但我可以理解!如何将每个循环结果仅放在一个变量中?例如,
$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
非常感谢, 刘
答案 0 :(得分:24)
答案 1 :(得分:9)
考虑在此特定情况下使用implode。
$string = implode(',', $employeeAges);
答案 2 :(得分:7)
您也可以尝试
$string = '';
foreach( $employeeAges as $value){
$string .= $value.',';
}
我试过了,它确实有效。
答案 3 :(得分:3)
foreach( $employeeAges as $key => $value){
$string .= $value.',';
}
每次循环都会重置字符串变量。对于每个循环迭代,执行上述操作将$ value连接到$ string。
答案 4 :(得分:2)
$string = "";
foreach( $employeeAges as $key => $value){
$string .= $value.',';
}
您每次都在重置变量,这将以空字符串开头并每次都附加一些内容。 但是有可能更好地完成这些任务的方法,例如implode。
答案 5 :(得分:2)
尝试
$string = '';
foreach( $employeeAges as $key => $value){
$string .= $value.',';
}
使用$ string = $ value。',';你每次都要覆盖$ string,所以你只得到最后一个值。
答案 6 :(得分:1)
答案 7 :(得分:1)
尝试此回显必须在内部,然后{}
变得正常
$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;
答案 8 :(得分:1)
输入:
$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'
有关以下内容的更多信息: