Check if a specific value exists at a specific key in any subarray of a multidimensional array

前端 未结 13 2189
梦毁少年i
梦毁少年i 2020-11-27 18:42

I need to search a multidimensional array for a specific value in any of the indexed subarrays.

In other words, I need to check a single column of the multidimension

13条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 19:16

    As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-

    Let say your 2-D array name $my_array and value to find is $id

    function idExists($needle='', $haystack=array()){
        //now go through each internal array
        foreach ($haystack as $item) {
            if ($item['id']===$needle) {
                return true;
            }
        }
        return false;
    }
    

    and to call it:

    idExists($id, $my_array);
    

    As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value

提交回复
热议问题