[英]How to remove every third element in a php array until only one element remains and print that element?
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 索引:0 1 2 3 4 5 6 7
value:1 2 3 4 5 6 7 8 值:1 2 3 4 5 6 7 8
this is the normal one 这是正常的
index:0 1 2 3 4 5 6 7 索引:0 1 2 3 4 5 6 7
value:1 2 4 5 7 8 值:1 2 4 5 7 8
here 3 and 6 removed as they came out as the 3rd elements 在这里,第3个元素和第6个元素作为第三个元素出现
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. 然后删除6之后,应该将7和8分别作为第一和第二,并将值1设为第3个元素,直到第一个元素剩余为止。
output 产量
12345678
1245678
124578
24578
2478
478
47
7
7 is the remaining element 7是剩余的元素
Your looking for array_chunk() 您在寻找array_chunk()
$a = array(1,2,3,4,5,6,7,8);
$thirds = array_chunk($a, 3);
$thirds now is like: 现在,三分之二的价格是:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
)
)
Then just loop through the $thirds array and array_pop() to grab the last value. 然后,只需遍历$ thirds数组和array_pop()即可获取最后一个值。
However, I'm not sure why you're looking to get 7 at the end and not 8. Can you explain? 但是,我不确定您为什么希望最后得到7,而不是8。您能解释一下吗?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.