Posted By

jatkins on 06/07/11


Tagged

search array String find multidimensional 2d


Versions (?)

Find the parent key of a value in a two-dimensional array


 / Published in: PHP
 

Released to the public domain. Example: you have an array, $seasons = array('Summer' => array('June', 'July', 'August'), 'Autumn' => array('September', 'October', 'November'), 'Winter' => array('December', 'January', 'February'), 'Spring' => array('March', 'April', 'May'));. Running print_r(find_keys_based_on_value('October', $seasons)); will is equivalent to print_r(array('Autumn' => array('September', 'October', 'November');. By default, the script will keep searching until it reaches the end of the array. To stop at the first match, call with $first_only set to true. To return only the key name(s), call with $key_names_only set to true.

  1. function find_keys_based_on_value($value, $array, $first_only = false, $key_names_only = false) {
  2. $results = array();
  3. foreach($array as $parent_key_name => $parent_key_values) {
  4. if(db::fast_is_array($parent_key_values)) {
  5. foreach($parent_key_values as $key_value) {
  6. if($key_value==$value) {
  7. if($first_only)
  8. return $key_names_only ? $parent_key_name : $parent_key_values; // return first key matched; exit function
  9. else
  10. $results[] = $key_names_only ? $parent_key_name : $parent_key_values; // keep result for output later
  11. }
  12. }
  13. }
  14. }
  15. return $results; // function will have stopped execution if $first_only = true, so it must be false
  16. }

Report this snippet  

You need to login to post a comment.