![](/img/trans.png)
[英]How to remove only one element from array in multiple duplicates in 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.