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条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面