Finding Array Rows with Column Values in a Flat Array
In this scenario, you are given two arrays: an original array, $arr1, with multiple columns, and a secondary array, $arr2, containing a list of unique ID values. The objective is to refine $arr1 by selecting only the rows that contain an ID value found within $arr2.
A highly efficient solution to this problem lies in utilizing the array_uintersect() function. This function employs a custom callback to compare elements from both input arrays. In this custom callback, we access values from the 'id' column. If that column is absent, we fall back to the parameter's value.
array_uintersect() leverages the technique of sorting during evaluation to optimize execution time. By comparing column values and ID values, it identifies the rows in $arr1 that have IDs found in $arr2. The resulting array will comprise only the select rows meeting this condition.
For your reference, below is the code that implements this solution:
var_export( array_uintersect( $arr1, $arr2, fn($a, $b) => ($a['id'] ?? $a) <=> ($b['id'] ?? $b) ) );
The above is the detailed content of How to Find Array Rows with Column Values in a Flat Array Using Array Functions?. For more information, please follow other related articles on the PHP Chinese website!