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

Share:
21,800
Seer
Author by

Seer

Updated on July 05, 2022

Comments

  • Seer
    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
    Seer over 12 years
    hmm I get "Invalid argument supplied for foreach()" which is shame as it looks like it will be exactly what I need :)
  • Seer
    Seer over 12 years
    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
    Eugen Rieck over 12 years
    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
    Seer over 12 years
    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; } }
  • Seer
    Seer over 12 years
    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!
  • Jonny White
    Jonny White over 12 years
    $clusters would need to be defined as your array of clusters as in the question
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.