tylerl
tylerl

Reputation: 1180

PHP - Use everything from 1st array, remove duplicates from 2nd?

I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:

1st Array

$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
    echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}

2nd Array

while( $secondResponseRow = $dbRequest->fetch_assoc() ){
    $secondResponseArray = array($secondResponseRow);
    foreach ($secondResponseArray as $secondResponseItem){
        echo $secondResponseItem['samecolumnname']; //This can't match anything above
    }
}

Thanks!

Upvotes: 0

Views: 85

Answers (3)

max-m
max-m

Reputation: 867

If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.

This code

<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);

print_r($a);
print_r($r);

produces the following output

[kernel@~]php so_1.php 
Array
(
    [0] => abc
    [1] => def
    [2] => ghi
    [3] => adg
)
Array
(
    [1] => hfs
    [2] => toast
    [3] => adgi
)
[kernel@~]

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

For example:

$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
    $response_names[] = $firstResponseItem['samecolumnname'];

while( $secondResponseRow = $dbRequest->fetch_assoc() ){
    $secondResponseArray = array($secondResponseRow);
    foreach ($secondResponseArray as $secondResponseItem) {
        if (!in_array($secondResponseItem['samecolumnname'], $response_names))
            $response_names[] = $secondResponseItem['samecolumnname'];
    }
}

array_walk($response_names, function($value) { echo $value . '<br />' });

Upvotes: 1

tkincher
tkincher

Reputation: 771

If I understand what you're looking to do and the arrays are in the same scope, this should work.

$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse); 
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
    echo $secondResponseItem['samecolumnname'];
}

Upvotes: 0

Related Questions