我有一个由如下信息组成的数组:
['Jay', 'Jay', 'Jay', 'Spiders', 'Dogs', 'Cats', 'John', 'John', 'John', 'Dogs', 'Cows', 'Snakes']
Run Code Online (Sandbox Code Playgroud)
我要做的是删除重复的条目,但前提是它们紧挨着彼此发生.
正确的结果应如下所示:
['Jay', 'Spiders', 'Dogs', 'Cats', 'John', 'Dogs', 'Cows', 'Snakes']
Run Code Online (Sandbox Code Playgroud)
我正在使用PHP,但任何类型的逻辑都能帮助我解决这个问题.
这是我到目前为止尝试过的一些代码:
$clean_pull = array();
$counter = 0;
$prev_value = NULL;
foreach($pull_list as $value) {
if ($counter == 0) {
$prev_value = $value;
$clean_pull[] = $value;
}
else {
if ($value != $pre_value) {
$pre_value = value;
}
}
echo $value . '<br>';
}
Run Code Online (Sandbox Code Playgroud)
弗朗西斯,当我运行以下代码时:
$lastval = end($pull_list);
for ($i=count($pull_list)-2; $i >= 0; $i--){
$thisval = $pull_list[$i];
if ($thisval===$lastval) {
unset($pull_list[$i]);
}
$lastval = $thisval;
}
# optional: reindex the array:
array_splice($pull_list, 0, 0);
var_export($pull_list);
Run Code Online (Sandbox Code Playgroud)
,我得到这些结果:
array ( 0 => 'NJ Lefler', 1 => 'Deadpool', 2 => 'NJ Lefler', 3 => 'Captain Universe: The Hero Who Could Be You', 4 => 'NJ Lefler', 5 => 'The Movement', 6 => 'NJ Lefler', 7 => 'The Dream Merchant', 8 => 'Nolan Lefler', 9 => 'Deadpool', 10 => 'Nolan Lefler', 11 => 'Captain Universe: The Hero Who Could Be You', 12 => 'Nolan Lefler', 13 => 'The Movement', 14 => 'Tom Smith', 15 => 'Deadpool', 16 => 'Tom Smith', 17 => 'Captain Universe: The Hero Who Could Be You', )
Run Code Online (Sandbox Code Playgroud)
您的方法($prev_value变量)应该正常工作,您不需要计数器.
你的使用$counter是你的代码不起作用的原因 - if语句的前半部分总是被执行,因为$counter它永远不会增加; 而下半部分只是比较价值观.您需要做的唯一事情是将当前值与之前的值进行比较,并且仅在它不同时包括当前值(或仅在它相同时才删除它).
如果使用功能减少,则更容易看到此算法.这是一个使用示例array_reduce:
$a = array('Jay', 'Jay', 'Jay', 'Spiders', 'Dogs', 'Cats', 'John', 'John', 'John', 'Dogs', 'Cows', 'Snakes');
$na = array_reduce($a, function($acc, $item){
if (end($acc)!==$item) {
$acc[] = $item;
}
return $acc;
}, array());
var_export($na);
Run Code Online (Sandbox Code Playgroud)
请注意var_export($a)(原始数组)和var_export($na)(代码生成的结果)的比较:
$a = array ( $na = array (
0 => 'Jay', 0 => 'Jay',
1 => 'Jay', 1 => 'Spiders',
2 => 'Jay', 2 => 'Dogs',
3 => 'Spiders', 3 => 'Cats',
4 => 'Dogs', 4 => 'John',
5 => 'Cats', 5 => 'Dogs',
6 => 'John', 6 => 'Cows',
7 => 'John', 7 => 'Snakes',
8 => 'John', )
9 => 'Dogs',
10 => 'Cows',
11 => 'Snakes',
)
Run Code Online (Sandbox Code Playgroud)
该array_reduce()方法与以下代码完全相同:
$na = array();
foreach ($a as $item) {
if (end($na)!==$item) {
$na[] = $item;
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用相同的算法就地修改数组,而不是返回数组的副本,但是从数组的末尾开始:
$lastval = end($a);
for ($i=count($a)-2; $i >= 0; $i--){
$thisval = $a[$i];
if ($thisval===$lastval) {
unset($a[$i]);
}
$lastval = $thisval;
}
# optional: reindex the array:
array_splice($a, 0, 0);
var_export($a);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |