Check if specific array key exists in multidimensional array - PHP

人走茶凉 提交于 2020-01-08 17:16:06

问题


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?


回答1:


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:


array_key_exists() is helpful.

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




回答3:


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

It can be helpful to do this to see the converted string: 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:

$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.

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":'




回答4:


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>';
}



回答5:


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

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



回答6:


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

$keySearch=22; // key seraching for

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:


First create a function for getting an array of all keys:

function array_keys_multi(array $array)
    {
        $keys = array();
        foreach($array as $key => $value) {
            $keys[] = $key;
            if (is_array($array[$key]))
                $keys = array_merge($keys, array_keys_multi($array[$key]));
        }
        return $keys;
    }

Then check for existence:

strpos(json_encode(array_keys_multi($array)), '"key"')



来源:https://stackoverflow.com/questions/19420715/check-if-specific-array-key-exists-in-multidimensional-array-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!