Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional Array - Search for value and get the sub-array

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)

like image 660
Seer Avatar asked Feb 14 '12 11:02

Seer


2 Answers

$search=202;

$cluster=false;

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

echo $cluster;
like image 180
Eugen Rieck Avatar answered Sep 22 '22 06:09

Eugen Rieck


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

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

$clusterX = array_search($clusterSubArr, $cluster);
like image 33
Aleksander Maj Avatar answered Sep 19 '22 06:09

Aleksander Maj