0

Possible Duplicate:
How to search by key=>value in a multidimensional array in PHP
PHP search for Key in multidimensional array

How can I search in a array values and get the key?

Example: search for id 1 = key 0 or search for name Frank = key 1

Array
(
    [0] => Array
    (
        [id] => 1
        [name] => Bob
        [url] => http://www.bob.com.br
    )

[1] => Array
    (
        [id] => 2
        [name] => Frank
        [url] => http://www.frank.com.br
    )
)

Thks. Adriano

Community
  • 1
  • 1
adrianogf
  • 171
  • 2
  • 12

3 Answers3

1

Use array_search

foreach($array as $value) {
    $result = array_search('Frank', $value);
    if($result !== false) break;
}
echo $result
m93a
  • 8,866
  • 9
  • 40
  • 58
Ruben Nagoga
  • 2,178
  • 1
  • 19
  • 30
0

If you do not know the depth, you can do something like the following, which employs the use of RecursiveIteratorIterator and RecursiveArrayIterator:

<?php
/*******************************
*   array_multi_search
*
*   @array  array to be searched
*   @input  search string
*
*   @return array(s) that match
******************************/
function array_multi_search($array, $input){
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));  

    foreach($iterator as $id => $sub){
        $subArray = $iterator->getSubIterator();  

        if(@strstr(strtolower($sub), strtolower($input))){
    $subArray = iterator_to_array($subArray);
            $outputArray[] = array_merge($subArray, array('Matched' => $id));
        }
    }  

    return $outputArray;
}
Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87
0

don't think there is a predifned function for that, but here is one:

function sub_array_search($array, $sub_key, $value, $strict = FALSE)
{
   foreach($array as $key => $sub_array)
   {
      if($sub_array[$sub_key] == $value)
      {
         if(!$strict OR $sub_array[$sub_key] === $value)
         {
            return $key;
         }
      }
   }

   return FALSE;
}
Puggan Se
  • 5,738
  • 2
  • 22
  • 48