Home  >  Article  >  Backend Development  >  How to Filter Array Rows by Matching Values from a Flat Array?

How to Filter Array Rows by Matching Values from a Flat Array?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 16:41:02312browse

How to Filter Array Rows by Matching Values from a Flat Array?

Finding Array Rows Matching Values in a Flat Array

In this scenario, you have an array, $arr1, with multiple columns, and a second array, $arr2, containing a set of ID values. The objective is to filter $arr1 and return only the rows that contain ID values present in $arr2.

An efficient solution to this problem lies in utilizing the array_uintersect() function, which performs a sorted intersection of two arrays using a custom callback function. This function operates on pairs of elements from both input arrays and returns -1, 0, or 1, based on the comparison result.

Custom Callback:

The custom callback function we define within array_uintersect() compares the ID column from $arr1 (if present) or the entire element itself if the column is not defined, with the value from $arr2.

<code class="php">fn($a, $b) => ($a['id'] ?? $a) <=> ($b['id'] ?? $b)</code>

Using the ternary operator, we assign $a['id'] to $a if the column exists, and $a itself otherwise. Similarly, we do the same for $b. This allows us to handle cases where the ID column may not be present in all rows.

Sorting and Efficiency:

Array_uintersect() utilizes sorting to compare elements efficiently. By default, it sorts both input arrays numerically. Since we are comparing ID values, which are likely numeric in your case, this sorting improves the execution time.

Example Usage:

To demonstrate how this solution works, we can apply it to the provided arrays:

<code class="php">$arr1 = [
    ['key' => 0, 'id' => 14, 'name' => 'bob', 'style' => 'big', 'age' => 33, 'whim' => 'no'],
    // ... (other rows from $arr1)
];

$arr2 = [14, 72, 8790];

$resultingArray = array_uintersect($arr1, $arr2, $customCallback);</code>

The $resultingArray will contain the rows from $arr1 where the ID values match those in $arr2.

The above is the detailed content of How to Filter Array Rows by Matching Values from a Flat Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn