douchensou6969 2010-11-03 16:03
浏览 10
已采纳

重构和使用计数器?

I have the following structure:

$text_1 = $this->getValue('value_1');
$text_2 = $this->getValue('value_2');
$text_3 = $this->getValue('value_3')

And also the following:

    foreach($text_1 as $t_1)
    {
        if(!$first)
        {
            $string_1 .= ",";

        }
        $first = false;
        $string_1 .= $t_1;
    }

    foreach($text_2 as $t_2)
    {
        if(!$first)
        {
            $string_2 .= ",";

        }
        $first = false;
        $string_2 .= $t_2;
    }

    foreach($text_3 as $t_3)
    {
        if(!$first)
        {
            $string_3 .= ",";

        }
        $first = false;
        $string_3 .= $t_3;
    }

I was wondering if this could be re-factored to use a counter, like in a for loop, to replace the _1, _2, _3 etc from my code?

  • 写回答

4条回答 默认 最新

  • duanquanhan2333 2010-11-05 08:52
    关注

    Ok so I figured out a way of doing it:

        for ($i=1;$i<=12;$i++) {
             $choices = $this->getValue('question_'.$i);
    
             $serialized = "";
             $first = true;
    
             foreach($choices as $choice)
             {
                if(!$first)
                {
                    $serialized .= ",";
                }
                $first = false;
                $serialized .= $choice;
            }
    
            $this->setValue('question_'.$i, $serialized);
    
         }
    

    This seems to work well!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下