Search code examples
phparraysobjectarray-difference

PHP array_dif() on 2 Arrays of Arrays


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)?


Solution

  • 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;
    }