2012-02-14 60 views
7

鉴于像PHP多维数组 - 查找值并获得子阵列

$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但它似乎只适用于单维数组吗? (即抱怨第二个参数是错误的dataype,如果我给它$簇)

非常感谢!

回答

10
$search=202; 

$cluster=false; 

foreach ($clusters as $n=>$c) 
    if (in_array($search, $c)) { 
    $cluster=$n; 
    break; 
    } 

echo $cluster; 
+0

中的群集数组。看起来你错过了一个支架或一些东西,我试图清理,但无法使它工作。 \t \t \t $ search = $ server; \t \t \t $ cluster = false; \t \t \t的foreach($簇$ N => $ C){ \t \t \t如果(in_array($搜索,$ C)){ \t \t \t $簇= $ N; \t \t \t break; \t \t \t} \t \t \t} \t \t \t打印( “方法2得到:” $簇); – Seer 2012-02-14 12:34:01

+0

刚刚在这里检查了我的代码,按预期工作。你的代码在最后一行是错误的,'print(“method 2 got:”$ cluster);'应该是'print(“method 2 got:$ cluster”);' – 2012-02-14 12:37:20

+0

绝对正确......但即使那样问题....我用202测试时,实际上我从示例中隐藏了REAL服务器名称以保护无辜:)工程太棒了! – Seer 2012-02-14 12:45:07

0
function getCluster($val) { 
    foreach($clusters as $cluster_name => $cluster) { 
     if(in_array($val, $cluster)) return $cluster_name; 
    } 
    return false; 
} 
+0

嗯,我得到这是耻辱,因为它看起来像它会正是我需要的:) – Seer 2012-02-14 12:28:04

+0

$集群需要“为的foreach()提供的无效参数”被定义为问题 – 2012-02-15 09:32:14

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)的键。没测试过,所以让我知道,如果这个工程

+0

这个不太合适,......空着。我所做的唯一改变是在函数的内容周围加上大括号。函数array_multi_search($ needle,$ haystack){ \t foreach($ haystack as $ key => $ data){ \t \t if(in_array($ needle,$ data))return $ key; \t} } – Seer 2012-02-14 12:40:29

+0

抱歉,错字。这现在起作用。 http://codepad.org/cnACdlFI – 2012-02-14 12:44:51

+0

肯定会 - 谢谢! – Seer 2012-02-14 13:11:53

1
$arrIt = new RecursiveArrayIterator($cluster); 
$server = 202; 

foreach ($arrIt as $sub){ 
    if (in_array($server,$sub)){ 
     $clusterSubArr = $sub; 
     break; 
     } 
    } 

$clusterX = array_search($clusterSubArr, $cluster);