PHP搜索多维数组以获取值&获得相应的元素值 [英] PHP Search multidimensional array for value & get corresponding element value

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

问题描述

我正在使用PHP&我有一个多维数组,需要搜索它才能查看键"的值是否存在,如果确实存在,则可以获取字段"的值.这是我的数组:

I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)

我希望能够在数组中搜索键"值31.如果存在,那么我希望能够提取"CONSTRUCTN"的相应字段"值.

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

我尝试使用array_search(31,$ myArray),但是它不起作用...

I've tried using array_search(31, $myArray) but it does not work...

推荐答案

function searchMultiArray($val, $array) {
  foreach ($array as $element) {
    if ($element['key'] == $val) {
      return $element['field'];
    }
  }
  return null;
}

然后:

searchMultiArray(31, $myArray);

应返回"CONSTRUCTN".

Should return "CONSTRUCTN".

这篇关于PHP搜索多维数组以获取值&获得相应的元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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