Multidimensional Array - Search for value and get the sub-array
21,800
Solution 1
$search=202;
$cluster=false;
foreach ($clusters as $n=>$c)
if (in_array($search, $c)) {
$cluster=$n;
break;
}
echo $cluster;
Solution 2
$arrIt = new RecursiveArrayIterator($cluster);
$server = 202;
foreach ($arrIt as $sub){
if (in_array($server,$sub)){
$clusterSubArr = $sub;
break;
}
}
$clusterX = array_search($clusterSubArr, $cluster);
Solution 3
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
Author by
Seer
Updated on July 05, 2022Comments
-
Seer almost 2 years
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)
-
Seer over 12 yearshmm I get "Invalid argument supplied for foreach()" which is shame as it looks like it will be exactly what I need :)
-
Seer over 12 yearssomething 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 over 12 yearsJust checked my code here, works as expected. Your code is wrong in the last line,
print("method 2 got: "$cluster);
should beprint("method 2 got: $cluster");
-
Seer over 12 yearsThis 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; } }
-
Seer over 12 yearsAbsolutely 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!
-
Jonny White over 12 years$clusters would need to be defined as your array of clusters as in the question
-
mickmackusa over 3 yearsThis answer is missing its educational explanation.