给出类似
的数组$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,则抱怨第二个参数是错误的dataype)
非常感谢!
答案 0 :(得分:11)
$search=202;
$cluster=false;
foreach ($clusters as $n=>$c)
if (in_array($search, $c)) {
$cluster=$n;
break;
}
echo $cluster;
答案 1 :(得分:2)
function array_multi_search($needle,$haystack){
foreach($haystack as $key=>$data){
if(in_array($needle,$data))
return $key;
}
}
$key=array_multi_search(202,$clusters);
echo $key;
$array=$clusters[$key];
尝试使用此功能。它返回$ haystack(cluster)的直接子数组中$ needle(202)的键。没有经过测试,请告诉我这是否有效
答案 2 :(得分:1)
$arrIt = new RecursiveArrayIterator($cluster);
$server = 202;
foreach ($arrIt as $sub){
if (in_array($server,$sub)){
$clusterSubArr = $sub;
break;
}
}
$clusterX = array_search($clusterSubArr, $cluster);
答案 3 :(得分:0)
function getCluster($val) {
foreach($clusters as $cluster_name => $cluster) {
if(in_array($val, $cluster)) return $cluster_name;
}
return false;
}