Given an array like
$clusters = array(
"clustera" => array(
'101',
'102',
'103',
'104'
),
"clusterb" => array(
'201',
'202',
'203',
'204'
),
"clusterc" => array(
'301',
'302',
'303',
'304'
)
);
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)
asked Feb 14, 2012 at 11:10
4 Answers 4
$search=202;
$cluster=false;
foreach ($clusters as $n=>$c)
if (in_array($search, $c)) {
$cluster=$n;
break;
}
echo $cluster;
answered Feb 14, 2012 at 11:14
Sign up to request clarification or add additional context in comments.
3 Comments
Seer
something funky going on. Seemed you missed a brace or something anfd I tried to clean up but can't get it working. $search=$server; $cluster=false; foreach ($clusters as $n=>$c) { if (in_array($search,$c)) { $cluster=$n; break; } } print("method 2 got: "$cluster);
Eugen Rieck
Just checked my code here, works as expected. Your code is wrong in the last line,
print("method 2 got: "$cluster);
should be print("method 2 got: $cluster");
Seer
Absolutely right ... but even that was not the issue .... I was testing with 202 when in fact I hid the REAL server name from the example to protect the innocent :) Works great!
$arrIt = new RecursiveArrayIterator($cluster);
$server = 202;
foreach ($arrIt as $sub){
if (in_array($server,$sub)){
$clusterSubArr = $sub;
break;
}
}
$clusterX = array_search($clusterSubArr, $cluster);
answered Jan 31, 2013 at 6:56
2 Comments
mickmackusa
This answer is missing its educational explanation.
Jose Manuel Abarca Rodríguez
Dear Aleksander Maj : would you add an explanation to your answer, please, it's not so easy to understand.
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];
Try using this function. It returns the key of the $needle(202) in the immediate child arrays of $haystack(cluster). Not tested, so let me know if this works
answered Feb 14, 2012 at 11:15
1 Comment
Seer
This one not quite working either ... comes up empty. The only change I have made is throwing braces around the contents of the function. function array_multi_search($needle,$haystack) { foreach($haystack as $key=>$data) { if(in_array($needle,$data)) return $key; } }
function getCluster($val) {
foreach($clusters as $cluster_name => $cluster) {
if(in_array($val, $cluster)) return $cluster_name;
}
return false;
}
answered Feb 14, 2012 at 11:13
2 Comments
Seer
hmm I get "Invalid argument supplied for foreach()" which is shame as it looks like it will be exactly what I need :)
Jonny White
$clusters would need to be defined as your array of clusters as in the question
lang-php