繁体   English   中英

如何删除php数组中的所有第三个元素,直到仅剩下一个元素并打印该元素?

[英]How to remove every third element in a php array until only one element remains and print that element?

数组是这样的

$a = array(1,2,3,4,5,6,7,8);

之后,在每次迭代中,应删除第三个元素,直到到达单个元素为止

迭代将是这样的

索引:0 1 2 3 4 5 6 7

值:1 2 3 4 5 6 7 8
这是正常的

索引:0 1 2 3 4 5 6 7

值:1 2 4 5 7 8
在这里,第3个元素和第6个元素作为第三个元素出现

然后删除6之后,应该将7和8分别作为第一和第二,并将值1设为第3个元素,直到第一个元素剩余为止。

产量

12345678

1245678

124578

24578

2478

478

47

7

7是剩余的元素

您在寻找array_chunk()

$a = array(1,2,3,4,5,6,7,8);
$thirds = array_chunk($a, 3);

现在,三分之二的价格是:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
        )   
)

然后,只需遍历$ thirds数组和array_pop()即可获取最后一个值。

但是,我不确定您为什么希望最后得到7,而不是8。您能解释一下吗?

这是代码,希望对您有所帮助。

<?php
$array = [1,2, 3,4,5,6,7,8];

function removeAtNth($array, $nth)
{
    $step = $nth - 1;       //gaps between operations
    $benchmark = 0;    
    while(isset($array[1]))
    {   
        $benchmark += $step;
        $benchmark = $benchmark > count($array) -1 ? $benchmark % count($array) : $benchmark;
        echo $benchmark."\n";
        unset($array[$benchmark]);
        $array = array_values($array);
        echo implode('', $array)."\n";
    }   
}

removeAtNth($array, 3); 

结果:

kris-roofe@krisroofe-Rev-station:~$ php test.php
1245678
124578
24578
2478
478
47
7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM