John Davidson

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

0 comments
Message:


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.



My Answer:
You can achieve the desired output by iterating through $array2 and checking for a match with $array1. Here's a sample code snippet to accomplish this:

php
$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 ($row['sr_no'] == $array1['sr_no'] && $row['batch_id'] == $array1['batch_id']) {
$result = $row;
break;
}
}

print_r($result);


This code will iterate through $array2 and check if the 'sr_no' and 'batch_id' values match with those in $array1. If a match is found, the matching row will be stored in $result and the loop will break. Finally, the $result will contain the expected output.

Rate this post

4 of 5 based on 6678 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us