0

I have an $array with build:

array(5) {
  [0]=>
  array(5) {
    ["woj"]=>
    string(4) "2"
    ["pow"]=>
    string(2) "11"
    ["gmi"]=>
    string(1) "2"
    ["rodz_gmi"]=>
    string(1) "2"
    ["name"]=>
    string(10) "Test1"
  }
  [1]=>
  array(5) {
    ["woj"]=>
    string(1) "2"
    ["pow"]=>
    string(2) "11"
    ["gmi"]=>
    string(1) "2"
    ["rodz_gmi"]=>
    string(1) "2"
    ["name"]=>
    string(8) "test2"
  }
  [2]=>
  array(5) {
    ["woj"]=>
    string(1) "2"
    ["pow"]=>
    string(2) "11"
    ["gmi"]=>
    string(1) "2"
    ["rodz_gmi"]=>
    string(1) "2"
    ["name"]=>
    string(12) "test3"
  }
  [3]=>
  array(5) {
    ["woj"]=>
    string(1) "2"
    ["pow"]=>
    string(2) "11"
    ["gmi"]=>
    string(1) "2"
    ["rodz_gmi"]=>
    string(1) "2"
    ["name"]=>
    string(8) "Test4"
  }
  [4]=>
  array(5) {
    ["woj"]=>
    string(1) "2"
    ["pow"]=>
    string(2) "11"
    ["gmi"]=>
    string(1) "2"
    ["rodz_gmi"]=>
    string(1) "2"
    ["name"]=>
    string(11) "Test5"
  }
}

and I want to create a php function, which can be search main array key by value (name). Example - search main array key by name: test3. Result should be 2, because second main key of $array contain subarray where name key = test3.

I tied with array_search, but with multidimensional array, this function not work.

Thanks for your help.

Pavvcio
  • 11
  • 5

1 Answers1

0

You may try the following for your multi-dimensional array:

function myCustomSearch($data,$searchVal){
     foreach($data as $index => $subArray){
          foreach($subArray as $key=>$value){
               if($value === $searchVal)return $index;
          }
     }
     return null; //return null if not found
}

eg use assuming your current array shared in question is stored in $data

$resultIndex = myCustomSearch($data,'test3');

Let me know if this works for you.

ggordon
  • 9,790
  • 2
  • 14
  • 27