简体   繁体   中英

Search value in multidimensional array in PHP

I am trying to search the value in an array. My array format is as below:

Array
(
    [2] => Array([0] => [HEADER])    
    [3] => Array([0] => "ACCESSION #"
                 [1] => "F4216027")    
    [4] => Array([0] => "ACTIVATION CODE"
                 [1] => "PGMWZ-PUSUU")
    [5] => Array([0] => "CUSTOMER FIRST NAME"
                 [1] => "JAMES")
);

If I am trying to search "CUSTOMER FIRST NAME" . I tried with below function. But no result

function searchForValue($id, $array) {
   foreach ($array as $key => $val) {
       if ($val[0] === $id) {
           return $key;
       }
   }
   return null;
}

And expected output is the key of parent index: [5]

Please help me to get out from this.

Simple solution using foreach and in_array function:

$search_word = "CUSTOMER FIRST NAME";
$parent_key = null;

// $arr is your initial array
foreach ($arr as $k => $v) {
    if (in_array($search_word, $v)) $parent_key = $k;
}

print_r($parent_key);  // 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM