Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

PHP multidimensional array search by value

<?php
// PHP program to carry out multidimensional array search
  
  
// Function to iteratively search for a given value
function searchForId($search_value, $array, $id_path) {
  
    // Iterating over main array
    foreach ($array as $key1 => $val1) {
  
        $temp_path = $id_path;
          
        // Adding current key to search path
        array_push($temp_path, $key1);
  
        // Check if this value is an array
        // with atleast one element
        if(is_array($val1) and count($val1)) {
  
            // Iterating over the nested array
            foreach ($val1 as $key2 => $val2) {
  
                if($val2 == $search_value) {
                          
                    // Adding current key to search path
                    array_push($temp_path, $key2);
                          
                    return join(" --> ", $temp_path);
                }
            }
        }
          
        elseif($val1 == $search_value) {
            return join(" --> ", $temp_path);
        }
    }
      
    return null;
}
  
// Multidimensional array 
$gfg_array = array(
    array(
        'score' => '100',
        'name' => 'Sam',
        'subject' => 'Data Structures'
    ),
    array(
        'score' => '50',
        'name' => 'Tanya',
        'subject' => 'Advanced Algorithms'
    ),
    array(
        'score' => '75',
        'name' => 'Jack',
        'subject' => 'Distributed Computing'
    )
);
  
$search_path = searchForId('Advanced Algorithms',
                    $gfg_array, array('$'));
  
print($search_path);
  
?>
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #PHP #multidimensional #array #search
ADD COMMENT
Topic
Name
3+2 =