在多维数组中查找值 [英] Find values in multidimensional arrays

查看:315
本文介绍了在多维数组中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组:

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

如何获取最喜欢玩的人(例如Mario)的用户名?

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

我的错:忘记明确提及"favoriteGame"值是动态的,我无法事先知道它是哪个.

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

我的解决方案:

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

遍历每个子数组并找到其最喜欢的游戏值. 如果还没有$ favoriteGame数组,则创建它. 将实际子数组的用户名值推送到$ favoriteGame数组.

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.

推荐答案

我会使用array_filter.如果您使用的是PHP 5.3或更高版本,则可以这样操作:

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

对于较旧的版本,这会有所不同,因为您将无法使用lambda函数.

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

这篇关于在多维数组中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆