在我的多维数组列表上搜索

时间:2018-03-11 14:21:17

标签: php arrays arraylist

我有这个数组:

Array
(
    [8008] => Array
        (
            [main_mob_vnum] => 8008
            [0] => Array
                (
                    [drop_mob_vnum] => 50300
                    [drop_mob_count] => 2
                    [drop_mob_percent] => 110.00
                )

            [1] => Array
                (
                    [drop_mob_vnum] => 39030
                    [drop_mob_count] => 2
                    [drop_mob_percent] => 85.00
                )
        )

    [8009] => Array
        (
            [main_mob_vnum] => 8009
            [0] => Array
                (
                    [drop_mob_vnum] => 50300
                    [drop_mob_count] => 4
                    [drop_mob_percent] => 110.00
                )

            [1] => Array
                (
                    [drop_mob_vnum] => 50125
                    [drop_mob_count] => 1
                    [drop_mob_percent] => 75.00
                )
        )

    [8010] => Array
        (
            [main_mob_vnum] => 8009
            [0] => Array
                (
                    [drop_mob_vnum] => 50125
                    [drop_mob_count] => 4
                    [drop_mob_percent] => 110.00
                )
        )
)

我想制作一个类似的功能 function searchArray($array,$vnum) if $vnum is == with drop_mob_vnum获取先前的数组并将所有这些数组键放在新数组

例如,searchArray($array,50300)应返回如下数组:array(8008,8009),因为8010没有drop_mob_vnum == 50300

我知道StackOverflow要求我用代码发布我的问题,但我不知道从哪里开始。如果有人可以帮助我,我会很感激。谢谢!

1 个答案:

答案 0 :(得分:1)

这个功能可以解决问题:

function find_vnum($array,$value)
{
    $result = array();

    foreach ($array AS $k1 => $v1)
    {
        foreach ($v1 AS $k2 => $v2)
        {
            if ($k2 === 'main_mob_vnum') {
                continue;
            }

            foreach ($v2 AS $k3 => $v3)
            {
                if ($k3 !== 'drop_mob_vnum') {
                    continue;
                }

                if (($v3 === $value) && !in_array($k1, $result)) {
                    $result[] = $k1;
                }
            }
        }
    }

    return $result;
}

给出您的样本数据:

print_r(find_vnum($data,50300));

// Array
// (
//    [0] => 8008
//    [1] => 8009
// )

您可以看到有效的演示here