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

StackOverflow https://stackoverflow.com/questions/23562016

Pergunta

I have three arrays

$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'];

I want to remove the first duplicates from $firstArray and based on the keys of the later encountered duplicates, I want to filter the other two arrays. i.e. in $firstArray the second duplicated elements begin from the 4th index, (4,5,6,7)

Expected Result

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

I used array_unique and array_values but it sort first duplicates.

Foi útil?

Solução

You can enjoy/abuse the effect that array_flip() has on an array containing duplicate values -- it will overwrite earlier encountered values with later encountered values.

After that, you can use three calls of array_diff_key() or just loop over the flipped data and access the data based on the remaining indexes.

Code: (Demo)

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

Or you could push references into the result arrays and keep overwriting the mapped values if they are re-encountered. (Demo)

$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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top