0

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!

2
  • array_diff or in_array Commented Jun 21, 2013 at 18:34
  • here $secondResponseArray = array($secondResponseRow); you are making it where the foreach will only ever have one element to go through. Commented Jun 21, 2013 at 18:38

3 Answers 3

1

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 />' });
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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@~]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.