搜索值并获取子数组

搜索值并获取子数组

本文介绍了PHP多维数组-搜索值并获取子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个像这样的数组

$clusters = array(
"clustera" => array(
    '101',
    '102',
    '103',
    '104'
),
"clusterb" => array(
    '201',
    '202',
    '203',
    '204'
),
"clusterc" => array(
    '301',
    '302',
    '303',
    '304'
)
);

如何搜索服务器(例如202)并找回其集群?即搜索202,响应为"clusterb",我尝试使用array_search,但似乎仅适用于一维数组,对吗? (即,如果我给第二个参数$ clusters,则抱怨第二个参数是错误的数据类型)

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)

非常感谢!

推荐答案

$search=202;

$cluster=false;

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

echo $cluster;

这篇关于PHP多维数组-搜索值并获取子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:58