phparraysmultidimensional-arrayfilteringarray-intersect

Filter associative rows in a 2d array using another 2d array which does not contain all columns


I'm using array_intersect for comparing two 2d arrays.

$myArray = array(
  array(
    'site_id'  => 'S6407', 
    'tssr_id'  => 'TSSRBOQ-200204-0145-59'
  ),
  array(
    'site_id'  => 'S5910', 
    'tssr_id'  => 'TSSRBOQ-200204-0145-8'
  ),
);

// $items_tssr is get from another variable
foreach ($items_tssr as $key => $value) {
    $array_validate[] = array(
        'site_id' => $value['site_id'],
        'tssr_id' => $value['no_tssr_boq_site']
    );
}

$result = array_map(
    'unserialize',
    array_intersect(
        array_map('serialize', $myArray),
        array_map('serialize', $array_validate)
    )
);
// if there are same 
if (array_key_exists(0, $result) {
    echo 'process this';
} else {
    echo 'dont process this';
}

My problem is that the original $myArray contains more columns than just 'site_id' and 'tssr_id'.

$myArray_origin = array(
    'site_id' => 'S6407',
    'tssr_id'  => 'TSSRBOQ-200204-0145-59'
    'site_name' => 'Site S6407',
    'id_site_doc'=> '127361,
    'implementation_id' => 'imp4121',
    'status' => "implementation_created",
    "endstate" => false
),
...

How do I filter the $myArray_origin array without throwing away a few of the values? $array_validate only contains 2 columns of data: 'site_id' and 'tssr_id'.


Solution

  • You could make use of array_filter + in_array instead. This will only keep the entries whose site_id and tssr_id are present in one of array_validate's own entries:

    $result = array_filter($myArray, function (array $entry) use ($array_validate): bool {
      return in_array([
        'site_id' => $entry['site_id'], 
        'tssr_id' => $entry['tssr_id']
      ], $array_validate, true);
    });
    

    Demo: https://3v4l.org/4Qhmr