PHP multidimensional array search by value

前端 未结 23 3334
情歌与酒
情歌与酒 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:31

    Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.

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

    Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.

        // Array Data Of Users
    $userdb = array (
        array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
        array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
        array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
    );
    
    // Obtain The Key Of The Array
    $arrayKey = searchArrayKeyVal("uid", '100', $userdb);
    if ($arrayKey!==false) {
        echo "Search Result: ", $userdb[$arrayKey]['name'];
    } else {
        echo "Search Result can not be found";
    }
    

    PHP Fiddle Example

提交回复
热议问题