PHP搜索数组A以匹配数组B中的id然后从数组B打印数据

时间:2010-10-02 13:23:58

标签: php

这是第一个数组输出的内容:

Array ( 
[0] => Array ( [id] => 67 [title] => avatar delete any ) 
[1] => Array ( [id] => 66 [title] => avatar edit any ) 
[2] => Array ( [id] => 65 [title] => avatar upload ) 
[3] => Array ( [id] => 8 [title] => comments edit own ) 
[4] => Array ( [id] => 6 [title] => comments post ) 
[5] => Array ( [id] => 9 [title] => comments remove own ) 
[6] => Array ( [id] => 7 [title] => comments vote ) 
[7] => Array ( [id] => 5 [title] => get other members emails )
[8] => Array ( [id] => 1 [title] => send greetings ) 
[9] => Array ( [id] => 4 [title] => send messages ) 
[10] => Array ( [id] => 64 [title] => use flip chat ) 
[11] => Array ( [id] => 11 [title] => videos add ) 
[12] => Array ( [id] => 13 [title] => videos approve ) 
[13] => Array ( [id] => 12 [title] => videos delete ) 
[14] => Array ( [id] => 14 [title] => videos edit ) 
[15] => Array ( [id] => 10 [title] => videos view ) 
[16] => Array ( [id] => 2 [title] => view profiles ) 
[17] => Array ( [id] => 3 [title] => vote ) )

第二个数组输出:

Array (
[2] => Array ( [id] => 2 [title] => view profiles [AllowedCount] => 5 [AllowedPeriodLen] => 5 ) 
[3] => Array ( [id] => 3 [title] => vote [AllowedCount] => 0 [AllowedPeriodLen] => 0 ) )

我正在使用foreach遍历第一个数组以显示已启用的操作。我如何检查第二个数组的Key是否与First的键匹配,然后从AllowedCount和AllowedPeriodLen中提供变量值?

2 个答案:

答案 0 :(得分:1)

我会重新考虑我的阵列设计 如果id确实是一个唯一的数字,那么将第一个数组重新设计为:

$arr1 = Array ( 
[67] => avatar delete any
[66] => avatar edit any  
... 
)

第二个就是那个

$arr2 = Array (
[2] => Array ( [title] => view profiles [AllowedCount] => 5 [AllowedPeriodLen] => 5 ) 
[3] => Array ( [title] => vote [AllowedCount] => 0 [AllowedPeriodLen] => 0 ) )

这样该行匹配id的

然后做一些像

这样的事情
foreach($arr2 as $key=>$element){
    echo $arr1[$key];
}

答案 1 :(得分:0)

这是有效的。 array_key_exists函数派上用场。

$bEnabled = array_key_exists($arr1['id'], $arr2);
if($bEnabled){
    $iNumAllowed = $arr2[$arr1['id']]['AllowedCount'];
}