如果内部数组中存在匹配,则获取外部数组的索引

时间:2015-04-18 09:14:52

标签: php mysql arrays

当我print_r我的数组给出

Array ( 
   [0] => Array ( [userid] => 2 [popularity] => 41.7 ) 
   [1] => Array ( [userid] => 5 [popularity] => 33.3 ) 
   [2] => Array ( [userid] => 7 [popularity] => 25.0 ) 
)

是在查询用户并按流行度desc排序后返回的数组,意思是
具有id 2 has popularity 41.7的用户,具有id 5 has popularity 33.3的用户等等,

然后我有一个动态查询,向每个用户展示他的受欢迎程度 例如:
user with id 2 has popularity of 41.7
                user with id 5 has popularity of 33.3

我想要的是显示每个用户的位置(外部数组index)如果动态查询的用户ID与上面的数组的输出匹配然后递增1,因为数组索引始终开始0 示例:
user with id 2, will have position of 1 (the winner)
user with id 5, will have position of 2         
user with id 7, will have position of 3等。

我该怎么做......

1 个答案:

答案 0 :(得分:2)

此代码修改数组和广告新键'position'(= $ key + 1)到每个元素。

function addPosition(&$item, $key) {
    $item['position'] = $key + 1;
}
array_walk($data, 'addPosition');