如何为while循环

时间:2018-04-29 18:44:53

标签: php angularjs

    $data1 = array();
    $final_ttt = "15";
    $items = [];
    for ($j = 1; $j <= $final_ttt; ++$j)
    {
    $TeamNo = "t$j";
    $items[] = $TeamNo;
    }
    print_r($items);

    In while loop im getting below values

    $day = 1;
    $i = 0;
    while($row = $qry->fetch()) 
    {
        $name = $row['name'];   //a,b,c,d
        $loopvalue = $row['loopvalue']; // getting 2,3,8,3,4

        $data1[]=array("name" => $name,"loopvalue" => $loopvalue);

        if( $i % $final_ttt == 0 )
        {
            $fday = "Day ".$day;
            $day++;
        }
    }

    output
name    value   Team                            day
a       2       t1,t12                          1
b       3       t3,t4,t5                        1           
c       8       t5,t6,t7,t8,t9,t10,t11,t12      1
d       3       t13,t14,t15                     1
e       4       t1,t2,t3,t4                     2

如何根据while循环值分配团队。如果我得到的价值是2 =&gt;然后我需要像这样分配前2队t1,t2。 kinldy帮帮我。

提前谢谢你

---我们正在编辑问题,因为提供的解决方案在某些测试用例中不起作用。就像附图中所示的一样。

enter image description here

以下是上图输出的更新代码

$lastIndex = 0;
$day = 1;
while($row = $qry->fetch()) 
{
    $name = $row['name'];   //a,b,c,d
    $loopvalue = $row['loopvalue']; // getting 2,3,8,3,4

    if($i==0)
    {
        $fday = "Day ".$day;//Day 1 for first Itration
        $day = 2;
    }

    $team = implode(',',array_slice($items, $lastIndex, $loopvalue));
    $lastIndex = $lastIndex + $loopvalue;

    if($lastIndex > count($items))
    {
        $lastIndex = $lastIndex - count($items);
        $team .= ','.implode(',',array_slice($items, 0, $lastIndex));

        $fday = "Day ".$day;
        $day++;
    }
    $data1[]=array("name" => $name,"loopvalue" => $loopvalue, "day" => $fday, 'team' => $team);
    $row ++;
}
print_r($data1);

1 个答案:

答案 0 :(得分:1)

您可以尝试以下内容

$lastIndex = 0;
while($row = $qry->fetch()) 
{
    $name = $row['name'];   //a,b,c,d
    $loopvalue = $row['loopvalue']; // getting 2,3,8,3,4

      $team = implode(',',array_slice($items, $lastIndex, $loopvalue));
      $lastIndex = $lastIndex + $loopvalue;
      if($lastIndex > count($items)) {
          $lastIndex = $lastIndex - count($items);
          $team .= ','.implode(',',array_slice($items, 0, $lastIndex));
       }    

        $data1[]=array("name" => $name,"loopvalue" => $loopvalue, 'team' => $team);
     $row ++;
    }

print_r($data1);

会导致

Array ( [0] => Array ( [name] => a [loopvalue] => 2 [team] => t1,t2 ) [1] => Array ( [name] => b [loopvalue] => 3 [team] => t3,t4,t5 ) [2] => Array ( [name] => c [loopvalue] => 8 [team] => t6,t7,t8,t9,t10,t11,t12,t13 ) [3] => Array ( [name] => d [loopvalue] => 3 [team] => t14,t15,t1 ) [4] => Array ( [name] => e [loopvalue] => 4 [team] => t2,t3,t4,t5 ) )

如果这可以解决您的问题,请告诉我。