5

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

LargeTuna
  • 2,694
  • 7
  • 46
  • 92

4 Answers4

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

gmc
  • 3,910
  • 2
  • 31
  • 44
6

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
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
blackandorangecat
  • 1,246
  • 5
  • 18
  • 37
0

One liner solution:

$result = is_numeric($res = array_search(31, array_column($myArray, 'key'))) ? $myArray[$res]["field"] : "";

array_search accepts 2 parameters i.e the value to be search and the array, subsequently I've provided the array which needs searching using array_column which gets that particular column from the array to be searched and is_numeric is used to make sure that valid key is returned so that result can displayed accordingly.

Kikloo
  • 11
  • 3
  • This should work: $result = is_numeric($res = array_search(31, array_column($myArray, 'key'))) ? $myArray[$res]["field"] : ""; – Kikloo Nov 14 '22 at 08:20
  • Because `array_column()` and `array_search()` both perform iterations on the input array, this approach is not likely to outperform a simple breakable `foreach()`. A `foreach()` will never do more than 1 loop over the input array and is capable of "short-circuiting". This answer possibly loops over the input 2 full times. – mickmackusa Nov 17 '22 at 06:22