在PHP中比较一维数组和多维数组的快速方法 [英] Fastes way to compare single-dimensional against multidimensional array in PHP
问题描述
我有一个像这样的多维数组:
I have a multidimensional array like this:
Array (
[0] => Array
(
[time] => 1364685993
[memberid] => 131
)
[1] => Array
(
[time] => 1364685994
[memberid] => 133
)
[2] => Array
(
[time] => 1364685995
[memberid] => 141
)
)
和像这样的一维数组:
Array (
[0] => 131
[1] => 141
[2] => 191
[3] => 205
)
现在我要从不包含普通数组中的memberid值的多维数组中删除所有子数组?
Now I want to remove all Sub-arrays from multidimensional arrays that DOES NOT contain the memberid value from normal array ?
在这种情况下,只有Subaray [1]要从多维数组中删除,因为它的"memberid"键值(133)在正常数组中不显示.这些数组实际上很大,所以我不确定最快的方法是什么?
In this case only Subaray[1] to be removed from multidimensional array as it's 'memberid' key value (133) doesn't show in normal array. Those arrays are actually pretty big, so I am not sure what would be fastest way to do it ?
推荐答案
首先,我将翻转$nomal
数组,以便在数组中获得恒定的查找时间,如下所示:
First, I would flip the $nomal
array to get constant lookup time into the array, like this:
$normal = array_flip( $normal);
然后,您只需要通过简单的查找就可以通过$normal
数组过滤$multidimensional_array
:
Then, you just have to filter the $multidimensional_array
by the $normal
array with a simple lookup:
$filtered = array_filter( $multidimensional_array, function( $el) use( $normal) {
return isset( $normal[ $el['member_id'] ]);
});
这篇关于在PHP中比较一维数组和多维数组的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!