Search code examples
phparraysintersectionarray-intersect

Filter 2D array by comparing column values against a differently-keyed column in another array


I have 2 arrays that I'm working with. The first array comes from the data of a CSV file and the other is a response from an API.

Is it possible to filter array 2 by using matching values from array 1?

Array 1 Example

[
    ["B00CEEZ57S"],
    ["B002QJZADK"],
    ["B001EHL2UK"],
    ["B003FSTNB6"],
]

Array 2 Example

[
    [
        "name" => "Jonathan Franzen: Purity (Hardcover); 2015 Edition",
        "ASIN" => "B002QJZADK"
    ],
    [
        "name" => "Cardinal Gates Outdoor Child Safety Gate, Brown",
        "ASIN" => "B00CE8C7SO"
    ],
    [
        "name" => "Sauder Edge Water 71.88\" Bookcase Estate Black Finish",
        "ASIN" => "B001EHL2UK"
    ],
    [
        "name" => "The Pioneer Woman 82695.03R Cowboy Rustic 8\" Rosewood Handle Can Opener, Scis...",
        "ASIN" => "B015LU7GPU"
    ]
]

These rows should be kept:

[
    'name' => 'Jonathan Franzen: Purity (Hardcover); 2015 Edition',
    'ASIN' => 'B002QJZADK',
],
[
    'name' => 'Sauder Edge Water 71.88" Bookcase Estate Black Finish',
    'ASIN' => 'B001EHL2UK'
]

Solution

  • Assuming the two arrays as $array1 and $array2 respectively, the following steps need to be followed:

    1. Convert $array1 to a 1 dimensional array $options because it's easier to check for values that way.
    2. Filter $array2 using array_filter() such that the value corresponding to 'ASIN' index matches with values contained in $options

      foreach ($array1 as $arr) {
          $options[] = current($arr);  // COnverted to 1-d array
          /* Result:  Array ( [0] => B00CEEZ57S [1] => B002QJZADK [2] => B001EHL2UK [3] => B003FSTNB6 )*/
      }
      
      /* Filter $array2 and obtain those results for which ['ASIN'] value matches with one of the values contained in $options */
      $result = array_filter($array2, function($v) use ($options) {
          return in_array($v['ASIN'], $options);
      });