$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;
}
<?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);
3条答案
按热度按时间unftdfkk1#
我拼凑了这个简单的循环,并用注解解释了它
$output
值jyztefdp2#
GrumpyCrouton的解决方案可能更简洁,但这里有另一种方法,基本上你把所有的值放在一个字符串中,然后使用字符串函数来完成这项工作。
代码带有注解性说明:
演示:https://3v4l.org/i1WKI
Using str_replace so that it only acts on the first match?的代码只替换了第一次出现在另一个字符串中的字符串。
cdmah0mi3#
我们可以使用一个数组来跟踪每一个被移除的项,然后使用array_shift移出该项并计数以限制循环溢出