Home  >  Article  >  Backend Development  >  How to Retain Array Rows with Matching Column Values from a Flat Array?

How to Retain Array Rows with Matching Column Values from a Flat Array?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 04:17:02436browse

How to Retain Array Rows with Matching Column Values from a Flat Array?

Retain Array Rows with Matching Column Values from a Separate Flat Array

Given an array $arr1 with multiple columns and a second flat array $arr2 containing a list of specific column values, the objective is to filter $arr1 and extract only the rows where the values in a particular column match the elements in $arr2.

Solution:

To efficiently perform this task, array_uintersect() can be employed. This native function utilizes a sorting algorithm during comparison to enhance execution speed. It takes two arrays and a custom callback function to determine the comparison logic.

In the provided code, the callback function leverages array destructuring to access the id column from each element of $arr1 and $arr2. If the id column does not exist, it defaults to the parameter's value.

The comparison checks if the id values from both arrays are equal, ensuring that the rows in $arr1 match the values in $arr2. The result is a new array containing only the desired rows from $arr1.

This approach offers superior performance to iterative calls of in_array() due to minimized function calls and optimized execution time.

The above is the detailed content of How to Retain Array Rows with Matching Column 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