PHP Search multidimensional array for value & get corresponding element value

亡梦爱人 提交于 2020-01-23 13:02:17

问题


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

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".

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


回答1:


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

And then:

searchMultiArray(31, $myArray);

Should return "CONSTRUCTN".




回答2:


One-line solution using array_column and array_search functions:

$result = array_search(31, array_column($arr, 'key', 'field'));

print_r($result);   // CONSTRUCTN

Or with simple foreach loop:

$search_key = 31;
$result = "";
foreach ($arr as $item) {   // $arr is your initial array
    if ($item['key'] == $search_key) {
        $result = $item['field'];
        break;
    }
}

print_r($result);   // CONSTRUCTN



回答3:


I haven't tested, but I think this should do it.

function searchByKey($value, $Array){
    foreach ($Array as $innerArray) {
        if ($innerArray['key'] == $value) {
            return $innerArray['field'];
        }
    }
}

Then calling searchByKey(31, $myArray); should return 'CONSTRUCTN'.

Hope that helps.




回答4:


You could use array_filter, something like this,

function searchMultiDimensionalArray($array, $key, $value) {
   $items = array_filter($array, function($item){
     return $item[$key] == $value;
  });
  if (count($items) > 0) {
    return $items[0];
  }
  return NULL;
}

And use it just like this for any multidimensional array,

$searchItem = searchMultiDimensionalArray($myArray, 'key', 31)

if ($searchItem != NULL) {
   $field = $searchItem['field']
}


来源:https://stackoverflow.com/questions/43173255/php-search-multidimensional-array-for-value-get-corresponding-element-value

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