Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two arrays of arrays containing a country name and a corresponding analytical metric. I need to subtract them (based on the first sub array value, i.e. the country) to return a third array of the countries found only in the first and not in the second. Example input and output:

First Array:

Array
(
    [0] => Array
        (
            [0] => Afghanistan
            [1] => 1
        )

    [1] => Array
        (
            [0] => Albania
            [1] => 1
        )
)

Second Array:

Array
(
    [0] => Array // not found in 1st array by country name
        (
            [0] => Australia
            [1] => 2
        )

    [1] => Array
        (
            [0] => Albania
            [1] => 2
        )
)

Intended Output

Array
(
    [0] => Array
        (
            [0] => Australia
            [1] => 2
        )
)

array_dif(); is returning no differences, despite there being many in my data sets. How can I go about creating this subtracted third array (in PHP)?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Try this

$array1=array('0'=>Array('0' => 'Afghanistan','1' => '1'),
        '1'=>Array('0' => 'Albania','1' => '1')     );
$array2 = Array('0' => Array ('0' => 'Australia','1' => '2'),
    '1' => Array('0' => 'Albania','1' => '2'));
$finalArray = diffArray($array1,$array2); //returns your expected result


function diffArray($array1,$array2){    
    $newarray = array();
    foreach ($array2 as $tmp){
        $duplicate = false;
        foreach($array1 as $tmp1){
            if ($tmp[0] == $tmp1[0]){
                $duplicate=true;
            } 
        }
        if(!$duplicate)
        $newarray[] = $tmp;
    }
    return $newarray;
}
share|improve this answer
    
Worked a treat - thank you! –  Ryan Brodie Jul 31 '12 at 8:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.