首页 > 解决方案 > 如何使用特定键在多维数组中查找特定值

问题描述

我有一个看起来像这样的数组

$myArray = Array
(
    [Standardbox] => Array
        (
            [details] => Array
                (
                    [name] => Standardbox
                )

            [resources] => Array
                (
                    [0] => Array
                        (
                            [resourceId] => 1
                            [resourceName] => Knife
                            [amount] => 1
                            [unit] => 2
                        )

                    [1] => Array
                        (
                            [resourceId] => 2
                            [resourceName] => Fork
                            [amount] => 1
                            [unit] => 2
                        )

                )

        )

)

我想检查数组中是否value存在(刀)的 1key resourceId

我在 stackoverflow 找到了一些函数,但没有什么真正适合我的目的:

这个看起来很有希望,但我认为它不认为数组是多维的:

function multi_key_in_array($needle, $haystack, $key) 
{
    foreach ($haystack as $h) 
    {
        if (array_key_exists($key, $h) && $h[$key]==$needle) 
        {
            return true;
        }
    }
    return false;
}

然后打电话

if(multi_key_in_array(1, $myArray, "resourceId"))
{
     // It is present in the array
}

非常感谢任何帮助!

标签: php

解决方案


<?php

function multi_key_in_array($needle, $haystack, $key) 
{
    foreach ($haystack as $h) 
    {
        if (array_key_exists($key, $h) && $h[$key]==$needle) 
        {
            return true;
        }
    }
    return false;
}


$myArray = Array
(
    'Standardbox' => Array
        (
            'details' => Array
                (
                    'name' => 'Standardbox'
                ),

            'resources' => Array
                (
                    0 => Array
                        (
                            'resourceId' => 1,
                            'resourceName' => 'Knife',
                            'amount' => 1,
                            'unit' => 2
                        ),

                    1 => Array
                        (
                            'resourceId' => 2,
                            'resourceName' => 'Fork',
                            'amount' => 1,
                            'unit' => 2
                        )

                )

        )

);


if(multi_key_in_array(1, $myArray['Standardbox']['resources'], "resourceId"))
{
     echo 'true';
} else {
    echo 'false';
}

> Blockquote

推荐阅读