php Checking if value exists in array of array

匿名 (未验证) 提交于 2019-12-03 02:18:01

问题:

I have an array within an array.

$a = array ( 0 => array ( 'value' => 'America', ), 1 => array ( 'value' => 'England', ), ) 

How do I check if 'America' exists in the array? The America array could be any key, and there could be any number of subarrays, so a generalized solution please.

Looking on the php manual I see in_array, but that only works for the top layer. so something like in_array("America", $a) would not work.

Thanks.

回答1:

A general solution would be:

function deep_in_array($needle, $haystack) {     if(in_array($needle, $haystack)) {         return true;     }     foreach($haystack as $element) {         if(is_array($element) && deep_in_array($needle, $element))             return true;     }     return false; } 

The reason why I chose to use in_array and a loop is: Before I examine deeper levels of the array structure, I make sure, that the searched value is not in the current level. This way, I hope the code to be faster than doing some kind of depth-first search method.


Of course if your array is always 2 dimensional and you only want to search in this kind of arrays, then this is faster:

function in_2d_array($needle, $haystack) {     foreach($haystack as $element) {         if(in_array($needle, $element))             return true;     }     return false; } 


回答2:

PHP doesn't have a native array_search_recursive() function, but you can define one:

function array_search_recursive($needle, $haystack) {     foreach ($haystack as $value) {         if (is_array($value) && array_search_recursive($needle, $value)) return true;         else if ($value == $needle) return true;     }     return false; } 

Untested but you get the idea.



回答3:

function search($a,$searchval){  //$a - array; $searchval - search value; if(is_array($a)) { foreach($a as $val){  if(is_array($val)) if(in_array($searchval,$val)) return true;   } } else return false; }  search($a, 'America'); //function call 


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