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

家住魔仙堡 提交于 2019-12-29 08:32:47

问题


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 it's 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 wrong dataype if I give it $clusters)

Many Thanks!


回答1:


$search=202;

$cluster=false;

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

echo $cluster;



回答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];

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




回答3:


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

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

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



回答4:


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


来源:https://stackoverflow.com/questions/9275832/php-multidimensional-array-search-for-value-and-get-the-sub-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!