[英]Save PHP ForEach Loop value in a Variable as Comma Separated String
[英]How to pass value by comma separated to a variable using foreach loop in codeigniter
在執行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;
?>
您的代碼中有很多錯誤
<?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;
?>
每個數組值不能有相同的位置
$aa=array("a" => 1, "b" => 2, "c" =>3, "d" => 4);
foreach($aa as $value)
{
$temp[]=$value;
}
echo implode(",",$temp);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.