Search for unique row in a multidimensional array using an associative array containing two elements

Viewed 78

I'm trying to get the values from the second array which match the associative elements from the first array.

$array1 can only possibly match one row (at most) with the qualifying sr_no and batch_id values because the combination of these two columns will always provide uniqueness. In other words, when a match is found, there will be no chance of making another match in the remaining data.

$array1 = ['sr_no' => 72, 'batch_id' => 1];

$array2 = [ 
    ['quantity' => 22, 'sr_no' => 71, 'batch_id' => 2, 'inq_id' => 91],
    ['quantity' => 35, 'sr_no' => 72, 'batch_id' => 1, 'inq_id' => 92],
    ['quantity' => 20, 'sr_no' => 69, 'batch_id' => 3, 'inq_id' => 90],  
];

Expected Output:

['quantity' => 35, 'sr_no' => 72, 'batch_id' => 1, 'inq_id' => 92]

I tried with $result = array_diff_assoc($array2, $array1);, but it's printing the entire $array2 array values.

1 Answers

You should stop iterating as soon as a match is found.

If your $array1 is designed to be flexible, use array_intersect_assoc() to return the matching elements, then check that all required matches are found.

Code: (Demo)

$array1 = ['sr_no' => 72, 'batch_id' => 1];

$array2 =
[ 
    ['quantity' => 22, 'sr_no' => 71, 'batch_id' => 2, 'inq_id' => 91],
    ['quantity' => 35, 'sr_no' => 72, 'batch_id' => 1, 'inq_id' => 92],
    ['quantity' => 20, 'sr_no' => 69, 'batch_id' => 3, 'inq_id' => 90],  
];

$result = null;
foreach ($array2 as $row) {
    if (array_intersect_assoc($array1, $row) === $array1) {
        $result = $row;
        break;
    }
}
var_export($result);

Output:

array (
  'quantity' => 35,
  'sr_no' => 72,
  'batch_id' => 1,
  'inq_id' => 92,
)
Related