Search array and return all keys and values when match found

前端 未结 3 1380
一生所求
一生所求 2021-01-01 22:18

I like to perform a search on an array and return all values when a match is found. The key [name] in the array is what I am doing a search on.

         


        
相关标签:
3条回答
  • 2021-01-01 22:42
    function search_array( $array, $name ){
        foreach( $array as $item ){
            if ( is_array( $item ) && isset( $item['name'] )){
                if ( $item['name'] == $name ){ // or other string comparison
                    return $item;
                }
            }
        }
        return FALSE; // or whatever else you'd like
    }
    
    0 讨论(0)
  • 2021-01-01 22:52

    I would like to offer an optional change to scibuff's answer(which was excellent). If you are not looking for an exact match, but a string inside the array...

    function array_search_x( $array, $name ){
        foreach( $array as $item ){
            if ( is_array( $item ) && isset( $item['name'] )){
                if (strpos($item['name'], $name) !== false) { // changed this line
                    return $item;
                }
            }
        }
        return FALSE; // or whatever else you'd like
    }
    

    Call this with...

    $pc_ct = array_search_x($your_array_name, 'your_string_here');
    
    0 讨论(0)
  • 2021-01-01 22:54
    $filteredArray = 
    array_filter($array, function($element) use($searchFor){
      return isset($element['name']) && $element['name'] == $searchFor;
    });
    

    Requires PHP 5.3.x

    0 讨论(0)
提交回复
热议问题