-1

I have 2 array, I need to compare both array, I tried with array_diff(), but its not working with multi-dimensional array. I need to compare both array and get the unique array values from given array. how can I compare both array in Laravel?

First array :

array:2 [▼
  0 => array:3 [▼
    "company_id" => "2"
    "product_id" => 48
    "combo_id" => 45
  ]
  1 => array:3 [▼
    "company_id" => "2"
    "product_id" => 48
    "combo_id" => 50
  ]
]

Second array :

array:2 [▼
  0 => array:3 [▼
    "company_id" => 2
    "product_id" => 48
    "combo_id" => 45
  ]
  1 => array:3 [▼
    "company_id" => 2
    "product_id" => 48
    "combo_id" => 60
  ]
]

If compare both aarry value, the second value is different, which "combo_id" => 50 but the seconds has "combo_id" => 60, so this array is not matrch with the second, I want this one as output

  • what output/result are you trying to get? – lagbox Aug 24 '20 at 10:43
  • @lagbox this is what i tried to compare `$x = array_diff($a, $b);` but got this error : _Array to string conversion_ then I found `array_diff()` function is not for multi-dimensional array –  Aug 24 '20 at 10:45
  • what do you want the result to look like or expect to get? – lagbox Aug 24 '20 at 10:47
  • @lagbox I added more on my question, hope you got it now –  Aug 24 '20 at 10:50
  • so you want an array like `['combo_id' => 60]`? – lagbox Aug 24 '20 at 12:50
  • @lagbox yes, if you see my both array, then `array:2 [▼` is match, but `1 => array:3 [▼` is not match with each other, so i need `1 => array:3 [▼` array –  Aug 24 '20 at 14:08

2 Answers2

1

if both arrays has same length then you can use for loop for it as below:

 $temp_array = [];
for($i = 0; $i < count($array1);$i++){
    $temp_array[] = (($array1[$i] == $array2[$i]) ? $array1[$i]: '');
}
print_r($temp_array);

this is just a sample code and you can customize it according to your needs

Naveed Ali
  • 1,043
  • 7
  • 15
0

Try this

function diff($a1, $a2) {
    if(is_array($a1) && is_array($a2)) {
        foreach ($a1 as $i => $v) {
            if(!isset($a2[$i])) return false;
            if(!diff($a1[$i], $a2[$i])) return false;
        }
        return true;
    }
    if(!is_array($a1) && !is_array($a2)) return $a1 == $a2;
    return false;
}
John V
  • 875
  • 6
  • 12