从1d数组中删除第一个重复项,同时保留后来遇到的值;然后过滤剩余元素映射的其他数组'索引


Remove first duplicates from a 1d array while preserving later encountered values; then filter other arrays mapped by the remaining elements' indexes

我有三个数组

$firstArray = ['22','24','23','26','22','24','23','26'];
$secondArray = ['John','Smith','Mark','Steve','George','Nick','Sean','Brad'];
$thirdArray = ['A','B','D','E','F','G','H'];

我想从$firstArray中删除第一个重复项,并基于后来遇到的重复项的键,我想过滤其他两个数组。例如,在$firstArray中,第二个重复元素从第4个索引(4,5,6,7)开始

预期结果

$newFirstArray = ['22','24','23','26'];
$newSecondArray = ['George','Nick','Sean','Brad'];
$newThirdArray = ['E','F','G','H'];

我使用array_uniquearray_values,但它首先排序重复。

您可以享受/滥用array_flip()对包含重复值的数组的影响——它将用后来遇到的值覆盖以前遇到的值。

之后,您可以使用三次array_diff_key()调用,或者只是在翻转的数据上循环,并基于剩余的索引访问数据。

代码(演示):

$new1 = [];
$new2 = [];
$new3 = [];
foreach (array_flip($firstArray) as $index) {
    $new1[] = $firstArray[$index];
    $new2[] = $secondArray[$index];
    $new3[] = $thirdArray[$index];
}
var_dump($new1, $new2, $new3);

或者您可以将引用推入结果数组,并在再次遇到映射值时继续覆盖它们。(演示)

$new1 = [];
$new2 = [];
$new3 = [];
foreach ($firstArray as $index => $value) {
    if (!isset($ref[$value])) {
        $new1[] = &$ref[$value][0];
        $new2[] = &$ref[$value][1];
        $new3[] = &$ref[$value][2];
    }
    $ref[$value][0] = $value;
    $ref[$value][1] = $secondArray[$index];
    $ref[$value][2] = $thirdArray[$index];
}
var_dump($new1, $new2, $new3);