Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Search multidimensional array for value & get corresponding element value

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

like image 709
LargeTuna Avatar asked Apr 02 '17 20:04

LargeTuna


2 Answers

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

like image 147
gmc Avatar answered Oct 09 '22 20:10

gmc


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
like image 42
RomanPerekhrest Avatar answered Oct 09 '22 19:10

RomanPerekhrest