dsfsad089111 2017-04-13 08:01
浏览 14
已采纳

文本爆炸和循环PHP结果是错误的

text to explode and loop php result is wrong but i try to this text to result 1 to 50 line but result is more duplicate

<?php
$text   = "1*10 11*20 21*30 31*40 41*50";
$textAr = explode("
", str_replace("", "", $text));
$textAr = array_filter($textAr, 'trim');
foreach ($textAr as $line) {
    $pieces = explode("*", $line);
    list($first, $last) = array_pad(explode('*', $line, 2), 2, null);
    $add = 1;
    for ($i = $first; $i <= $last; $i += $add) {
        $array[] = array(
            'count' => $i
        );
    }
    $codes = $array;
    foreach ($codes as $code) {
        echo $code['count'];
        echo "<br>";
    }
}
?>

Results : 150 lines

1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,‌​17,18,19,20,1,2,3,4,‌​5,6,7,8,9,10,11,12,1‌​3,14,15,16,17,18,19,‌​20,21,22,23,24,25,26‌​,27,28,29,30,1,2,3,4‌​,5,6,7,8,9,10,11,12,‌​13,14,15,16,17,18,19‌​,20,21,22,23,24,25,2‌​6,27,28,29,30,31,32,‌​33,34,35,36,37,38,39‌​,40,1,2,3,4,5,6,7,8,‌​9,10,11,12,13,14,15,‌​16,17,18,19,20,21,22‌​,23,24,25,26,27,28,2‌​9,30,31,32,33,34,35,‌​36,37,38,39,40,41,42‌​,43,44,45,46,47,48,4‌​9,50

but I want results but i want result 1-50 with no duplicates

  • 写回答

1条回答 默认 最新

  • doulu8537 2017-04-13 08:19
    关注

    You just need to move the print outside of the foreach loop. This code will add the number from 1 to 10, 11 to 20 .. etc according to the input [which is $text]. And print all of them at the end.

    <?php
    $text   = "1*10
    11*20
    21*30
    31*40
    41*50";
    $textAr = explode("
    ", str_replace("", "", $text));
    $textAr = array_filter($textAr, 'trim');
    
    foreach ($textAr as $line) {
        $pieces = explode("*", $line);
        list($first, $last) = array_pad(explode('*', $line, 2), 2, null);
    
        $add = 1;
        for ($i = $first; $i <= $last; $i += $add) {
            $array[] = array(
                'count' => $i
            );
        }
    
    
    }
    
    $codes = $array;
    foreach ($codes as $code) {
        echo $code['count'];
        echo "<br>";
    }
    ?>
    

    Result :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50

    Example : http://ideone.com/Tk052M

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法