doq1969 2009-10-28 22:42
浏览 55
已采纳

使用implode对while循环中获取的信息进行分组

I am having the following problem. I have the numbers 1/2/3/4/5/6 and I want to separate them into two groups 1/3/5 and 2/4/6. The selection must take place based on the position. This part works ok. The problem comes when I want to group them again, when I use the implode function; it only sees the last number that was stored. I know it has something to do with me using this notation (I chose this way since the amount of numbers to classify varies every time):

$q++;
$row0 = $row0 + 2;
$row1 = $row1 + 2;

but I can't figure a way to fix it or another way to get the same result. Hopefully someone here can point me in the right direction. I left the complete code below.


<?
$string = "1/2/3/4/5/6";
$splitted = explode("/",$string);
$cnt = count($splitted);
$q=0;
$row0=0;
$row1=1;
while($cnt > 2*$q)
{
  $p_row = implode(array($splitted[$row0]));
  echo "$p_row <br>";
  $i_row = implode(array($splitted[$row1]));
  echo "$i_row <br>";

  $q++;
  $row0 = $row0 + 2;
  $row1 = $row1 + 2;
}
$out = "implode(',', $i_row)";
var_dump($out);
?>

  • 写回答

3条回答 默认 最新

  • doukefu1361 2009-10-28 22:50
    关注

    You can split the array into groups using % on loop index. Put each group in separate array. Here is example:

    <?php
        $string = "1/2/3/4/5/6";
        $splitted = explode("/",$string);
        $group_odd = array();  ## all odd elements of $splitted come here
        $group_even = array(); ## all even elements of $splitted come here
        for ($index = 0; $index < count($splitted); ++$index) {
            ## if number is divided by 2 with rest then it's odd
            ## but we've started calculation from 0, so we need to add 1
            if (($index+1) % 2) { 
                $group_odd[] = $splitted[$index];
            }
            else {
                $group_even[] = $splitted[$index];
            }
        }
        echo implode('/', $group_odd), "<br />";  ## outputs "1/3/5<br />"
        echo implode('/', $group_even), "<br />"; ## outputs "2/4/6<br />"
        print_r($group_odd);
        print_r($group_even);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿