检查多维数组中是否存在特定的数组键 - PHP

时间:2022-11-01 21:31:09

I have a multidimensional array e.g. (this can be many levels deep):

我有一个多维数组,例如(这可以是很多层次):

$array = Array ( 
    [21] => Array ( ) 
    [24] => Array ( 
        [22] => Array ( ) 
        [25] => Array ( 
            [26] => Array ( ) 
        ) 
    ) 
) 

I am trying to loop through it to see if a certain key exists:

我试图循环它,看看是否存在某个键:

$keySearch = 22; // key searching for

function findKey($array, $keySearch) {
    foreach ($array as $item){
        if (isset($item[$keySearch]) && false === findKey($item[$keySearch], $item)){
            echo 'yes, it exists';
        }
    }
}

findKey($array, $keySearch);

But it finds nothing. Is there an error in the loop?

但它一无所获。循环中是否有错误?

7 个解决方案

#1


28  

I played with your code to get it working :

我玩了你的代码让它工作:

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            echo 'yes, it exists';
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}

#2


33  

array_key_exists() is helpful.

array_key_exists()很有帮助。

Then something like this:

然后这样的事情:

function multiKeyExists(array $arr, $key) {

    // is in base array?
    if (array_key_exists($key, $arr)) {
        return true;
    }

    // check arrays contained in this array
    foreach ($arr as $element) {
        if (is_array($element)) {
            if (multiKeyExists($element, $key)) {
                return true;
            }
        }

    }

    return false;
}

Working example: http://codepad.org/GU0qG5su

工作示例:http://codepad.org/GU0qG5su

#3


3  

function findKey($array, $keySearch)
{
    // check if it's even an array
    if (!is_array($array)) return false;

    // key exists
    if (array_key_exists($keySearch, $array)) return true;

    // key isn't in this array, go deeper
    foreach($array as $key => $val)
    {
        // return true if it's found
        if (findKey($val, $keySearch)) return true;
    }

    return false;
}

// test
$array = Array ( 
    21 => Array ( 24 => 'ok' ),
    24 => Array ( 
        22 => Array ( 29 => 'ok' ),
        25 => Array ( 
            26 => Array ( 32 => 'ok' ) 
        )
    )
);

$findKeys = Array(21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
foreach ($findKeys as $key)
{
    echo (findKey($array, $key)) ? 'found ' : 'not found ';
    echo $key.'<br>';
}

#4


1  

returns false if doesn't exists, returns the first instance if does;

如果不存在则返回false,如果返回则返回第一个实例;

function searchArray( array $array, $search )
{
    while( $array ) {
        if( isset( $array[ $search ] ) ) return $array[ $search ];
            $segment = array_shift( $array );
            if( is_array( $segment ) ) {
                if( $return = searchArray( $segment, $search ) ) return $return;
            }
        }
    }
    return false;
}

#5


1  

Here is a one line solution:

这是一个单行解决方案:

echo strpos(json_encode($array), $key) > 0 ? "found" : "not found";

This converts the array to a string containing the JSON equivalent, then it uses that string as the haystack argument of the strpos() function and it uses $key as the needle argument ($key is the value to find in the JSON string).

这会将数组转换为包含JSON等效的字符串,然后使用该字符串作为strpos()函数的haystack参数,并使用$ key作为needle参数($ key是要在JSON字符串中查找的值)。

It can be helpful to do this to see the converted string: echo json_encode($array);

这样做有助于查看转换后的字符串:echo json_encode($ array);

Be sure to enclose the needle argument in single quotes then double quotes because the name portion of the name/value pair in the JSON string will appear with double quotes around it. For instance, if looking for 22 in the array below then $key = '"22"' will give the correct result of not found in this array:

确保将needle参数括在单引号中,然后用双引号括起来,因为JSON字符串中名称/值对的名称部分将在其周围出现双引号。例如,如果在下面的数组中查找22,那么$ key ='“22”将给出在此数组中找不到的正确结果:

$array =
Array ( 
        21 => Array ( ), 
        24 => 
        Array ( 
            522 => Array ( ),
            25 =>
                Array ( 
                26 => Array ( ) 
            )
        )
    );

However, if the single quotes are left off, as in $key = "22" then an incorrect result of found will result for the array above.

但是,如果单引号保留,如$ key =“22”那么上面的数组将导致找到不正确的结果。

EDIT: A further improvement would be to search for $key = '"22":'; just incase a value of "22" exists in the array. ie. 27 => "22" In addition, this approach is not bullet proof. An incorrect found could result if any of the array's values contain the string '"22":'

编辑:进一步改进将是搜索$ key ='“22”:';只是在数组中存在值“22”。即。 27 =>“22”此外,这种方法不是防弹的。如果任何数组的值包含字符串'“22”,则可能导致发现错误:

#6


1  

For sure some errors, is this roughly what you are after? (Untested code):

肯定有些错误,这大致是你追求的吗? (未经测试的代码):

$keySearch=22; // key seraching for

$ keySearch = 22; //密钥搜索

function findKey($array, $keySearch) 
{ 
    // check whether input is an array
    if(is_array($array)
    {
       foreach ($array as $item)
       {
         if (isset($item[$keySearch]) || findKey($item, $keysearch) === true)
          {
            echo 'yes, it exists';
            return true;
          }
       }
    }
}

#7


0  

You can write it in one line of code! yes!

你可以用一行代码编写它!是!

str_contains(json_encode($array), 'key')

str_contains(json_encode($ array),'key')

#1


28  

I played with your code to get it working :

我玩了你的代码让它工作:

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            echo 'yes, it exists';
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}

#2


33  

array_key_exists() is helpful.

array_key_exists()很有帮助。

Then something like this:

然后这样的事情:

function multiKeyExists(array $arr, $key) {

    // is in base array?
    if (array_key_exists($key, $arr)) {
        return true;
    }

    // check arrays contained in this array
    foreach ($arr as $element) {
        if (is_array($element)) {
            if (multiKeyExists($element, $key)) {
                return true;
            }
        }

    }

    return false;
}

Working example: http://codepad.org/GU0qG5su

工作示例:http://codepad.org/GU0qG5su

#3


3  

function findKey($array, $keySearch)
{
    // check if it's even an array
    if (!is_array($array)) return false;

    // key exists
    if (array_key_exists($keySearch, $array)) return true;

    // key isn't in this array, go deeper
    foreach($array as $key => $val)
    {
        // return true if it's found
        if (findKey($val, $keySearch)) return true;
    }

    return false;
}

// test
$array = Array ( 
    21 => Array ( 24 => 'ok' ),
    24 => Array ( 
        22 => Array ( 29 => 'ok' ),
        25 => Array ( 
            26 => Array ( 32 => 'ok' ) 
        )
    )
);

$findKeys = Array(21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
foreach ($findKeys as $key)
{
    echo (findKey($array, $key)) ? 'found ' : 'not found ';
    echo $key.'<br>';
}

#4


1  

returns false if doesn't exists, returns the first instance if does;

如果不存在则返回false,如果返回则返回第一个实例;

function searchArray( array $array, $search )
{
    while( $array ) {
        if( isset( $array[ $search ] ) ) return $array[ $search ];
            $segment = array_shift( $array );
            if( is_array( $segment ) ) {
                if( $return = searchArray( $segment, $search ) ) return $return;
            }
        }
    }
    return false;
}

#5


1  

Here is a one line solution:

这是一个单行解决方案:

echo strpos(json_encode($array), $key) > 0 ? "found" : "not found";

This converts the array to a string containing the JSON equivalent, then it uses that string as the haystack argument of the strpos() function and it uses $key as the needle argument ($key is the value to find in the JSON string).

这会将数组转换为包含JSON等效的字符串,然后使用该字符串作为strpos()函数的haystack参数,并使用$ key作为needle参数($ key是要在JSON字符串中查找的值)。

It can be helpful to do this to see the converted string: echo json_encode($array);

这样做有助于查看转换后的字符串:echo json_encode($ array);

Be sure to enclose the needle argument in single quotes then double quotes because the name portion of the name/value pair in the JSON string will appear with double quotes around it. For instance, if looking for 22 in the array below then $key = '"22"' will give the correct result of not found in this array:

确保将needle参数括在单引号中,然后用双引号括起来,因为JSON字符串中名称/值对的名称部分将在其周围出现双引号。例如,如果在下面的数组中查找22,那么$ key ='“22”将给出在此数组中找不到的正确结果:

$array =
Array ( 
        21 => Array ( ), 
        24 => 
        Array ( 
            522 => Array ( ),
            25 =>
                Array ( 
                26 => Array ( ) 
            )
        )
    );

However, if the single quotes are left off, as in $key = "22" then an incorrect result of found will result for the array above.

但是,如果单引号保留,如$ key =“22”那么上面的数组将导致找到不正确的结果。

EDIT: A further improvement would be to search for $key = '"22":'; just incase a value of "22" exists in the array. ie. 27 => "22" In addition, this approach is not bullet proof. An incorrect found could result if any of the array's values contain the string '"22":'

编辑:进一步改进将是搜索$ key ='“22”:';只是在数组中存在值“22”。即。 27 =>“22”此外,这种方法不是防弹的。如果任何数组的值包含字符串'“22”,则可能导致发现错误:

#6


1  

For sure some errors, is this roughly what you are after? (Untested code):

肯定有些错误,这大致是你追求的吗? (未经测试的代码):

$keySearch=22; // key seraching for

$ keySearch = 22; //密钥搜索

function findKey($array, $keySearch) 
{ 
    // check whether input is an array
    if(is_array($array)
    {
       foreach ($array as $item)
       {
         if (isset($item[$keySearch]) || findKey($item, $keysearch) === true)
          {
            echo 'yes, it exists';
            return true;
          }
       }
    }
}

#7


0  

You can write it in one line of code! yes!

你可以用一行代码编写它!是!

str_contains(json_encode($array), 'key')

str_contains(json_encode($ array),'key')