php - 保留在第二个平面数组中找到列值的数组行

标签 php arrays filter array-filter array-intersect

** 我对此进行了编辑以展示我如何使用 array_search 让我的代码工作

我有一个数组,$arr1 有 5 列:

 key    id  name    style   age whim
 0      14  bob     big     33  no
 1      72  jill    big     22  yes
 2      39  sue     yes     111 yes
 3      994 lucy    small   23  no
 4      15  sis     med     24  no
 5      16  maj     med     87  yes
 6      879 Ike     larg    56  no
 7      286 Jed     big     23  yes

这个数组在缓存中,而不是数据库中。

然后我有第二个数组,其中包含一个 id 值列表 -

$arr2 = array(0=>14, 1=>72, 2=>8790)

如何过滤 $arr1 以便它只返回 ID 值在 $arr2 中的行?

我的代码按如下方式工作:

$arr1 = new CachedStuff();  // get cache

$resultingArray = [];  // create an empty array to hold rows
$filter_function = function ($row) use ($arr2) {
    return (array_search($row['id'], $arr2));
};
$resultingArrayIDs = $arr1->GetIds($filter_function, $resultingArray);

这给了我两个输出:$resultingArray 和 $resultingArrayIDs,它们都代表 $arr1 和 $arr2 的交集。

最佳答案

这整个任务只需一个巧妙的本地函数调用 -- array_uintersect() 即可完成。

因为自定义回调中的两个比较参数可能来自输入数组,请尝试从 id 列访问,如果没有一个 declered,则回退到参数的值。

在引擎盖下,此函数在评估时执行排序,以此作为缩短执行时间/处理速度的一种方式。我希望这种方法纯粹从最小化函数调用的角度来看优于 in_array() 的迭代调用。

代码:(Demo)

var_export(
    array_uintersect(
        $arr1,
        $arr2,
        fn($a, $b) =>
            ($a['id'] ?? $a)
            <=>
            ($b['id'] ?? $b)
    )
);

关于php - 保留在第二个平面数组中找到列值的数组行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47503473/

相关文章:

phpunit - 返回两个对象到下一个测试用例

javascript - 在文本字段中输入时显示预制建议列表

php - 在 php/mysql 中跟踪记录更新之间的变化

java - 循环数组以存储使用前一个元素的值

c# - 使用数组 c# 中的值过滤数据表

asp.net-mvc-3 - 如何在 MVC3 中输入时过滤职业

php - 无法连接到 MySQL 数据库 - PHP

c - 动态内存分配 - 二维数组

arrays - vb.net - 列表(字符串)排序,数字升序,字母降序

r - 如果字符串包含某些字符,则过滤和子集(在 R 中)