如何在代码点火器中使用foreach循环将逗号分隔的值传递给变量



在执行foreach循环后,我有一个包含一些值的数组。我想通过逗号分隔将每个值传递给一个变量,但最后一个值不应该带有逗号(,(。

<?php
$aa=array("id"=>1,"id"=>2,"id"=>3,"id"=>4);

$otherV = '';
foreach($aa as $key => $value){
if (!empty($otherV))
{
$otherV = $value.",";
}
else{
$otherV = $value;
}
}

echo $otherV;
?>

预期产量我想要这样的输出:1,2,3,4

试试这个:

<?php
$aaray=array("a"=>1,"b"=>2,"c"=>3,"d"=>4);
$otherV = '';
$len = count($aaray);
$i=0;
foreach($aaray as $value){
$i++;
//check if this is not the last iteration of foreach
//then add the `,` after concatenation 
if ($i != $len) {
$otherV .= $value.",";
}else{
//check if this is the last iteration of foreach
//then don't add the `,` after concatenation 
$otherV .= $value;
}  
}
echo $otherV;
?>

每个数组值不能有相同的位置

$aa=array("a" => 1, "b" => 2, "c" =>3, "d" => 4);
foreach($aa as $value)
{
$temp[]=$value;
}
echo implode(",",$temp);

代码中有许多错误

<?php
// fix array creation, dont use `->` use `=>`
// and the keys cannot all be the same
$aa=array("a"=>1,"b"=>2,"c"=>3,"d"=>4);
$otherV = '';
foreach($aa as $key => $value){
//concatenate the value into otherV using .=
$otherV .= $value.",";
}
rtrim( $otherV, ',');  // remove last comma
echo $otherV;
?>

最新更新