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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭