PHP multidimensional array search by value

前端 未结 23 3213
情歌与酒
情歌与酒 2020-11-21 04:45

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

<
相关标签:
23条回答
  • 2020-11-21 05:45

    I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.

    Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.

    Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.

     /**
         * @param array multidimensional 
         * @param string value to search for, ie a specific field name like name_first
         * @param string associative key to find it in, ie field_name
         * 
         * @return array keys.
         */
         function search_revisions($dataArray, $search_value, $key_to_search) {
            // This function will search the revisions for a certain value
            // related to the associative key you are looking for.
            $keys = array();
            foreach ($dataArray as $key => $cur_value) {
                if ($cur_value[$key_to_search] == $search_value) {
                    $keys[] = $key;
                }
            }
            return $keys;
        }
    

    Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.

    This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).

    /**
     * @param array multidimensional 
     * @param string $search_value The value to search for, ie a specific 'Taylor'
     * @param string $key_to_search The associative key to find it in, ie first_name
     * @param string $other_matching_key The associative key to find in the matches for employed
     * @param string $other_matching_value The value to find in that matching associative key, ie true
     * 
     * @return array keys, ie all the people with the first name 'Taylor' that are employed.
     */
     function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
        // This function will search the revisions for a certain value
        // related to the associative key you are looking for.
        $keys = array();
        foreach ($dataArray as $key => $cur_value) {
            if ($cur_value[$key_to_search] == $search_value) {
                if (isset($other_matching_key) && isset($other_matching_value)) {
                    if ($cur_value[$other_matching_key] == $other_matching_value) {
                        $keys[] = $key;
                    }
                } else {
                    // I must keep in mind that some searches may have multiple
                    // matches and others would not, so leave it open with no continues.
                    $keys[] = $key;
                }
            }
        }
        return $keys;
    }
    

    Use of function

    $data = array(
        array(
            'cust_group' => 6,
            'price' => 13.21,
            'price_qty' => 5
        ),
        array(
            'cust_group' => 8,
            'price' => 15.25,
            'price_qty' => 4
        ),
        array(
            'cust_group' => 8,
            'price' => 12.75,
            'price_qty' => 10
        )
    );
    
    $findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
    print_r($findKey);
    

    Result

    Array ( [0] => 2 ) 
    
    0 讨论(0)
  • 2020-11-21 05:46

    Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):

    function searcharray($value, $key, $array) {
       foreach ($array as $k => $val) {
           if ($val[$key] == $value) {
               return $k;
           }
       }
       return null;
    }
    

    Usage: $results = searcharray('searchvalue', searchkey, $array);

    0 讨论(0)
  • 2020-11-21 05:46

    I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not

    $arr = array(
        array(
            'title' => 'abc'
        )
    );
    

    Then i can use this

    $res = array_search('abc', array_column($arr, 'title'));
    if($res == ''){
        echo 'exists';
    } else {
        echo 'notExists';
    }
    

    I think This is the Most simple way to define

    0 讨论(0)
  • 2020-11-21 05:47

    Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:

     function searchArrayKeyVal($sKey, $id, $array) {
        foreach ($array as $key => $val) {
            if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
                return $key;
            }
        }
             return false;
     }
    

    For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"

    0 讨论(0)
  • 2020-11-21 05:50

    If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.

    If you want just one result:

    $key = array_search(40489, array_column($userdb, 'uid'));
    

    For multiple results

    $keys = array_keys(array_column($userdb, 'uid'), 40489);
    

    In case you have an associative array as pointed in the comments you could make it with:

    $keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
    

    If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!

    Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!

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