Search Multidimensional Array in PHP

前端 未结 2 1268
感动是毒
感动是毒 2021-01-16 06:14

How can I search the following multidimensional array for the string \'uk\'?

array(43)
{
  [0]=> array(1) { [\"country\"]=> string(9) \"Australia\" }
          


        
相关标签:
2条回答
  • 2021-01-16 06:26

    If you are using (PHP 5 >= 5.5.0) there is a better and simple way:

    if(array_search('UK', array_column($array, 'country')) !== false ){
        echo 'found';
    }else{
        echo 'Not found';
    }
    
    0 讨论(0)
  • 2021-01-16 06:27

    1) Why are you encapsulating all your simple strings in a new array?

    1a) If there actually is a reason:

    function my_search($needle, $haystack)
    {
        foreach($haystack as $k => $v)
        {
            if ($v["country"] == $needle)
                return $k;
        }
        return FALSE;
    }
    
    $key = my_search("uk", $yourArray);
    if($key !== FALSE)
    {
        ...
    } else {
        echo "Not Found.";
    }
    

    This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

    1b) if there isn't:

    2) Fix your array using simple strings as values, not array(1)'s of strings

    3) If it's fixed, you can simply use array_search()

    Edit: Changed arguments to resemble array_search more.

    0 讨论(0)
提交回复
热议问题