我在PHP中有两个数组,如下所示:
人:
Array
(
[0] => 3
[1] => 20
)
Run Code Online (Sandbox Code Playgroud)
诚征罪犯:
Array
(
[0] => 2
[1] => 4
[2] => 8
[3] => 11
[4] => 12
[5] => 13
[6] => 14
[7] => 15
[8] => 16
[9] => 17
[10] => 18
[11] => 19
[12] => 20
)
Run Code Online (Sandbox Code Playgroud)
如何检查是否所有的的人们元素是在通缉犯阵列?
在这个例子中,它应该返回,true因为20在Wanted Criminals中.
提前致谢.
Gre*_*reg 173
你可以用array_intersect().
$result = !empty(array_intersect($people, $criminals));
Run Code Online (Sandbox Code Playgroud)
pap*_*psy 29
使用array_intersect()和count()(而不是空)没有什么问题.
例如:
$bFound = (count(array_intersect($criminals, $people))) ? true : false;
Run Code Online (Sandbox Code Playgroud)
iht*_*tus 23
如果'空'不是最好的选择,那么这个:
if (array_intersect($people, $criminals)) {...} //when found
Run Code Online (Sandbox Code Playgroud)
要么
if (!array_intersect($people, $criminals)) {...} //when not found
Run Code Online (Sandbox Code Playgroud)
Pau*_*nis 21
该代码无效,因为您只能将变量传递给语言结构.empty()是一种语言结构.
你必须分两行:
$result = array_intersect($people, $criminals);
$result = !empty($result);
Run Code Online (Sandbox Code Playgroud)
Fra*_*rte 16
in_array与array_intersect的性能测试:
$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);
$a2 = array(3,20);
$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
/***** TEST ONE array_intersect *******/
$t = microtime(true);
for($i = 0; $i < 100000; $i++)
{
$x = array_intersect($a1,$a2);
$x = empty($x);
}
$intersect_times[] = microtime(true) - $t;
/***** TEST TWO in_array *******/
$t2 = microtime(true);
for($i = 0; $i < 100000; $i++)
{
$x = false;
foreach($a2 as $v){
if(in_array($v,$a1))
{
$x = true;
break;
}
}
}
$in_array_times[] = microtime(true) - $t2;
}
echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;
Run Code Online (Sandbox Code Playgroud)
结果如下:
0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354
0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906
Run Code Online (Sandbox Code Playgroud)
in_array至少快5倍.请注意,我们会在找到结果后立即"中断".
| 归档时间: |
|
| 查看次数: |
85656 次 |
| 最近记录: |