【问题标题】:How to pass value by comma separated to a variable using foreach loop in codeigniter如何使用codeigniter中的foreach循环将逗号分隔的值传递给变量
【发布时间】:2019-04-20 13:25:27
【问题描述】:

在执行 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

【问题讨论】:

  • 什么是-&gt;?你的意思是=&gt;

标签: php codeigniter


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      你的代码有很多错误

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

      【讨论】:

      • 我想要所有值,但您的代码只显示最后一个值
      • 打错了,刷新页面后再查看
      • 仍然遇到同样的问题
      • 啊,:) 错过了错误的数组创建。你不能有 4 个项目都具有相同的键 ::)
      猜你喜欢
      • 1970-01-01
      • 2020-07-10
      • 2023-03-30
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2016-01-01
      • 1970-01-01
      相关资源
      最近更新 更多