douguyi3903 2012-05-30 07:35
浏览 76
已采纳

在多维数组中查找值

I've a multidimensional array:

array (
    array (
        "username"        => "foo",
        "favoriteGame"    => "Mario"
    )
    array (
        "username"        => "bar",
        "favoriteGame"    => "Mario"
    )
    array (
        "username"        => "xyz",
        "favoriteGame"    => "Zelda"
    )
)

How could I get the usernames of the persons that like to play for example Mario the easiest way possible?

EDIT: My fault: forget to explicitly mention that the "favoriteGame" value is dynamic and I cannot know which it is in advance.

My Solution:

foreach($users as $key => $value)
{
    if(!isset($$value['favoriteGame']))
    {
        $$value['favoriteGame'] = array();
    }
    array_push($$value['favoriteGame'], $value['username']);
}

Iterate over each sub-array and find its favoriteGame value. If there is not already an array $favoriteGame create it. Push the username-value of the actual sub-array to the $favoriteGame array.

Thanks for your replies, I just couldn't phrase this question properly.

  • 写回答

7条回答 默认 最新

  • duanjian3920 2012-05-30 07:45
    关注

    I would use array_filter. If you have PHP 5.3 or up, you can do it like this:

    $favorite = "Mario";
    $filter = function($player) use($favorite) { return $player['favoriteGame'] == $favorite; };
    $filtered = array_filter($players, $filter);
    

    It will be a little different for older versions because you won't be able to use lambda functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?