Merge and diff arrays of arrays to find common values

  • A+
Category:Languages

I am trying to loop through several database table structures and determine the common structure (ie what columns are identical). The final structure should only show common columns, so if any table has a unique column, it should not be in the final array.

This is an example of what three table structures may look like.

$arr1 = [     ["name"=>"col1", "type"=>"varchar"],     ["name"=>"col2", "type"=>"int"]     ]; $arr2 = [     ["name"=>"col1", "type"=>"varchar"],     ["name"=>"col2", "type"=>"int"]    ,     ["name"=>"col3", "type"=>"date"]     ]; $arr3 = [     ["name"=>"col1", "type"=>"varchar"],     ["name"=>"col3", "type"=>"int"]     ];  $arrays = [$arr1, $arr2, $arr3]; 

Using array_merge, array_diff, array_intersect, or a loop, is it possible to determine which of these columns are common to all tables?

The end value should be [["name"=>"col1", "type"=>"varchar"]]

 


You can use a custom compare method with array_uintersect():

$arr1 = [     ["name" => "col1", "type" => "varchar"],     ["name" => "col2", "type" => "int"] ]; $arr2 = [     ["name" => "col1", "type" => "varchar"],     ["name" => "col2", "type" => "int"],     ["name" => "col3", "type" => "date"] ]; $arr3 = [     ["name" => "col1", "type" => "varchar"],     ["name" => "col3", "type" => "int"] ];  $common_columns = array_uintersect($arr1, $arr2, $arr3, 'compareDeepValue');  print_r($common_columns);  function compareDeepValue($val1, $val2) {     return (strcasecmp(serialize($val1), serialize($val2))) ; } 

Will output:

Array (     [0] => Array         (             [name] => col1             [type] => varchar         )  ) 

Note:

@Abracadaver made a good point this method will only work correctly when you have the array conventions in the same order.

Than you can for example use this:

function compareDeepValue($val1, $val2) {     return ($val1['name'] === $val2['name'] && $val1['type'] === $val2['type']) ? 0 : -1; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: