php 如何仅删除一次在数组中出现多次的单词

bvjxkvbb  于 2023-01-08  发布在  PHP
关注(0)|答案(3)|浏览(123)

我已经研究了各种方法,但我还没有找到解决这个问题的办法。
基本上,我必须查看单词是否重复,然后删除数组中第一次出现的单词。例如:

$array_words = ['harmony', 'Acrobat', 'harmony', 'harmony'];

我如何检查重复的单词,只检查一次,留下这样的数组:

$array_final = ['Acrobat', 'harmony', 'harmony'];
unftdfkk

unftdfkk1#

我拼凑了这个简单的循环,并用注解解释了它

$array_words = ['harmony', 'Acrobat', 'harmony', 'harmony'];

//get a count of each word in the array
$counted_values = array_count_values($array_words);

//hold the words we have already checked
$checked_words = [];

//variable to hold our output after filtering
$output = [];

//loop over words in array
foreach($array_words as $word) {

    //if word has not been checked, and appears more than once
    if(!in_array($word, $checked_words) && $counted_values[$word] > 1) {
        
        //add word to checked list, continue to next word in array
        $checked_words[] = $word;
        continue;

    }

    //add word to output
    $output[] = $word;
}

$output

Array
(
    [0] => Acrobat
    [1] => harmony
    [2] => harmony
)
jyztefdp

jyztefdp2#

GrumpyCrouton的解决方案可能更简洁,但这里有另一种方法,基本上你把所有的值放在一个字符串中,然后使用字符串函数来完成这项工作。
代码带有注解性说明:

<?php

$array_words = ['harmony', 'Acrobat', 'harmony', 'harmony'];
$array_words_unique = array_unique($array_words); //get a list of unique words from the original array
$array_str = implode(",", $array_words);

foreach ($array_words_unique as $word) {
    //count how many times the word occurs
    $count = substr_count($array_str, $word);
    
    //if it occurs more than once, remove the first occurence
    if ($count > 1) {
        //find the first position of the word in the string, then replace that with nothing
        $pos = strpos($array_str, $word); 
        $array_str = substr_replace($array_str, "", $pos, strlen($word));
    }
}

//convert back to an array, and filter any blank entries caused by commas with nothing between them
$array_final = array_filter(explode(",", $array_str));

var_dump($array_final);

演示:https://3v4l.org/i1WKI
Using str_replace so that it only acts on the first match?的代码只替换了第一次出现在另一个字符串中的字符串。

cdmah0mi

cdmah0mi3#

我们可以使用一个数组来跟踪每一个被移除的项,然后使用array_shift移出该项并计数以限制循环溢出

<?php

$record = ['harmony','harmony', 'Acrobat', 'harmony', 'harmony','last'];

for($i=0,$count=count($record),$stack=array();$i<$count;$i++){
    $item = array_shift($record);
    in_array($item,$record) && !in_array($item,$stack) 
    ? array_push($stack,$item) 
    : array_push($record,$item);
}

var_dump($record);

相关问题