Search Multidimensional Array in PHP

前端 未结 2 1307
感动是毒
感动是毒 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: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.

提交回复
热议问题