如何删除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);
之后,在每次迭代中,应删除第三个元素,直到到达单个元素
迭代将是这样的
index: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和2nd并转到值1,这使1成为第3个元素。这一过程一直持续到只有一个元素为止
输出
12345678
1245678
124578
24578
2478
478
47
7
7是剩余元素
< php
$ array = [1,2,3,4,5,6,7,8];
函数removeAtNth($ array,$ nth)
{
$ step = $ nth-1; //操作之间的间隙
$ 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
The array is like this
$a = array(1,2,3,4,5,6,7,8);
After that in each iteration the 3rd element should be removed until it reaches to a single element
the iteration will be something like this
index:0 1 2 3 4 5 6 7
value:1 2 3 4 5 6 7 8
this is the normal one
index:0 1 2 3 4 5 6 7
value:1 2 4 5 7 8
here 3 and 6 removed as they came out as the 3rd elements
then after 6 is removed it should count 7 and 8 as 1st and 2nd and go to value 1 which makes 1 as the 3rd element.This continues until there is only one element remaining.
output
12345678
1245678
124578
24578
2478
478
47
7
7 is the remaining element
here is the code, hope it helps.
<?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);
result:
kris-roofe@krisroofe-Rev-station:~$ php test.php
1245678
124578
24578
2478
478
47
7
这篇关于如何删除php数组中的所有第三个元素,直到仅剩一个元素并打印该元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!