多维数组 - 搜索值并获取子数组 [英] Multidimensional Array - Search for value and get the sub-array

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

问题描述

给定一个数组

$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 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)

推荐答案

$search=202;

$cluster=false;

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

echo $cluster;

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆