多维数组 - 搜索值并获取子数组
问题描述:
给定一个数组
$clusters = array(
"clustera" => array(
'101',
'102',
'103',
'104'
),
"clusterb" => array(
'201',
'202',
'203',
'204'
),
"clusterc" => array(
'301',
'302',
'303',
'304'
)
);
如何搜索服务器(例如 202)并取回其集群?即搜索 202 并且响应是clusterb";我尝试使用 array_search 但它似乎只适用于单维数组,对吗?(即抱怨第二个参数是错误的数据类型,如果我给它 $clusters)
How can I search for a server (e.g. 202) and get back its cluster? i.e. search for 202 and the response is "clusterb" I tried using array_search but it seems that is only for monodimensional arrays right? (i.e. complains that second argument is the wrong datatype if I give it $clusters)
答
$search=202;
$cluster=false;
foreach ($clusters as $n=>$c)
if (in_array($search, $c)) {
$cluster=$n;
break;
}
echo $cluster;