How to Find Array Rows with Column Values in a Flat Array Using Array Functions?

DDD
Release: 2024-10-23 17:59:02
Original
992 people have browsed it

How to Find Array Rows with Column Values in a Flat Array Using Array Functions?

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)
    )
);
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!